]> git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Source/C/GenFw/Elf64Convert.c
BaseTools/GenFw: ignore dynamic RELA sections
[mirror_edk2.git] / BaseTools / Source / C / GenFw / Elf64Convert.c
1 /** @file
2 Elf64 convert solution
3
4 Copyright (c) 2010 - 2014, Intel Corporation. All rights reserved.<BR>
5 Portions copyright (c) 2013-2014, ARM Ltd. All rights reserved.<BR>
6
7 This program and the accompanying materials are licensed and made available
8 under the terms and conditions of the BSD License which accompanies this
9 distribution. The full text of the license may be found at
10 http://opensource.org/licenses/bsd-license.php
11
12 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
13 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
14
15 **/
16
17 #include "WinNtInclude.h"
18
19 #ifndef __GNUC__
20 #include <windows.h>
21 #include <io.h>
22 #endif
23 #include <assert.h>
24 #include <stdbool.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <time.h>
29 #include <ctype.h>
30
31 #include <Common/UefiBaseTypes.h>
32 #include <IndustryStandard/PeImage.h>
33
34 #include "PeCoffLib.h"
35 #include "EfiUtilityMsgs.h"
36
37 #include "GenFw.h"
38 #include "ElfConvert.h"
39 #include "Elf64Convert.h"
40
41 STATIC
42 VOID
43 ScanSections64 (
44 VOID
45 );
46
47 STATIC
48 BOOLEAN
49 WriteSections64 (
50 SECTION_FILTER_TYPES FilterType
51 );
52
53 STATIC
54 VOID
55 WriteRelocations64 (
56 VOID
57 );
58
59 STATIC
60 VOID
61 WriteDebug64 (
62 VOID
63 );
64
65 STATIC
66 VOID
67 SetImageSize64 (
68 VOID
69 );
70
71 STATIC
72 VOID
73 CleanUp64 (
74 VOID
75 );
76
77 //
78 // Rename ELF32 strucutres to common names to help when porting to ELF64.
79 //
80 typedef Elf64_Shdr Elf_Shdr;
81 typedef Elf64_Ehdr Elf_Ehdr;
82 typedef Elf64_Rel Elf_Rel;
83 typedef Elf64_Rela Elf_Rela;
84 typedef Elf64_Sym Elf_Sym;
85 typedef Elf64_Phdr Elf_Phdr;
86 typedef Elf64_Dyn Elf_Dyn;
87 #define ELFCLASS ELFCLASS64
88 #define ELF_R_TYPE(r) ELF64_R_TYPE(r)
89 #define ELF_R_SYM(r) ELF64_R_SYM(r)
90
91 //
92 // Well known ELF structures.
93 //
94 STATIC Elf_Ehdr *mEhdr;
95 STATIC Elf_Shdr *mShdrBase;
96 STATIC Elf_Phdr *mPhdrBase;
97
98 //
99 // Coff information
100 //
101 STATIC UINT32 mCoffAlignment = 0x20;
102
103 //
104 // PE section alignment.
105 //
106 STATIC const UINT16 mCoffNbrSections = 4;
107
108 //
109 // ELF sections to offset in Coff file.
110 //
111 STATIC UINT32 *mCoffSectionsOffset = NULL;
112
113 //
114 // Offsets in COFF file
115 //
116 STATIC UINT32 mNtHdrOffset;
117 STATIC UINT32 mTextOffset;
118 STATIC UINT32 mDataOffset;
119 STATIC UINT32 mHiiRsrcOffset;
120 STATIC UINT32 mRelocOffset;
121 STATIC UINT32 mDebugOffset;
122
123 //
124 // Initialization Function
125 //
126 BOOLEAN
127 InitializeElf64 (
128 UINT8 *FileBuffer,
129 ELF_FUNCTION_TABLE *ElfFunctions
130 )
131 {
132 //
133 // Initialize data pointer and structures.
134 //
135 VerboseMsg ("Set EHDR");
136 mEhdr = (Elf_Ehdr*) FileBuffer;
137
138 //
139 // Check the ELF64 specific header information.
140 //
141 VerboseMsg ("Check ELF64 Header Information");
142 if (mEhdr->e_ident[EI_CLASS] != ELFCLASS64) {
143 Error (NULL, 0, 3000, "Unsupported", "ELF EI_DATA not ELFCLASS64");
144 return FALSE;
145 }
146 if (mEhdr->e_ident[EI_DATA] != ELFDATA2LSB) {
147 Error (NULL, 0, 3000, "Unsupported", "ELF EI_DATA not ELFDATA2LSB");
148 return FALSE;
149 }
150 if ((mEhdr->e_type != ET_EXEC) && (mEhdr->e_type != ET_DYN)) {
151 Error (NULL, 0, 3000, "Unsupported", "ELF e_type not ET_EXEC or ET_DYN");
152 return FALSE;
153 }
154 if (!((mEhdr->e_machine == EM_X86_64) || (mEhdr->e_machine == EM_AARCH64))) {
155 Error (NULL, 0, 3000, "Unsupported", "ELF e_machine not EM_X86_64 or EM_AARCH64");
156 return FALSE;
157 }
158 if (mEhdr->e_version != EV_CURRENT) {
159 Error (NULL, 0, 3000, "Unsupported", "ELF e_version (%u) not EV_CURRENT (%d)", (unsigned) mEhdr->e_version, EV_CURRENT);
160 return FALSE;
161 }
162
163 //
164 // Update section header pointers
165 //
166 VerboseMsg ("Update Header Pointers");
167 mShdrBase = (Elf_Shdr *)((UINT8 *)mEhdr + mEhdr->e_shoff);
168 mPhdrBase = (Elf_Phdr *)((UINT8 *)mEhdr + mEhdr->e_phoff);
169
170 //
171 // Create COFF Section offset buffer and zero.
172 //
173 VerboseMsg ("Create COFF Section Offset Buffer");
174 mCoffSectionsOffset = (UINT32 *)malloc(mEhdr->e_shnum * sizeof (UINT32));
175 memset(mCoffSectionsOffset, 0, mEhdr->e_shnum * sizeof(UINT32));
176
177 //
178 // Fill in function pointers.
179 //
180 VerboseMsg ("Fill in Function Pointers");
181 ElfFunctions->ScanSections = ScanSections64;
182 ElfFunctions->WriteSections = WriteSections64;
183 ElfFunctions->WriteRelocations = WriteRelocations64;
184 ElfFunctions->WriteDebug = WriteDebug64;
185 ElfFunctions->SetImageSize = SetImageSize64;
186 ElfFunctions->CleanUp = CleanUp64;
187
188 return TRUE;
189 }
190
191
192 //
193 // Header by Index functions
194 //
195 STATIC
196 Elf_Shdr*
197 GetShdrByIndex (
198 UINT32 Num
199 )
200 {
201 if (Num >= mEhdr->e_shnum) {
202 Error (NULL, 0, 3000, "Invalid", "GetShdrByIndex: Index %u is too high.", Num);
203 exit(EXIT_FAILURE);
204 }
205
206 return (Elf_Shdr*)((UINT8*)mShdrBase + Num * mEhdr->e_shentsize);
207 }
208
209 STATIC
210 UINT32
211 CoffAlign (
212 UINT32 Offset
213 )
214 {
215 return (Offset + mCoffAlignment - 1) & ~(mCoffAlignment - 1);
216 }
217
218 STATIC
219 UINT32
220 DebugRvaAlign (
221 UINT32 Offset
222 )
223 {
224 return (Offset + 3) & ~3;
225 }
226
227 //
228 // filter functions
229 //
230 STATIC
231 BOOLEAN
232 IsTextShdr (
233 Elf_Shdr *Shdr
234 )
235 {
236 return (BOOLEAN) ((Shdr->sh_flags & (SHF_WRITE | SHF_ALLOC)) == SHF_ALLOC);
237 }
238
239 STATIC
240 BOOLEAN
241 IsHiiRsrcShdr (
242 Elf_Shdr *Shdr
243 )
244 {
245 Elf_Shdr *Namedr = GetShdrByIndex(mEhdr->e_shstrndx);
246
247 return (BOOLEAN) (strcmp((CHAR8*)mEhdr + Namedr->sh_offset + Shdr->sh_name, ELF_HII_SECTION_NAME) == 0);
248 }
249
250 STATIC
251 BOOLEAN
252 IsDataShdr (
253 Elf_Shdr *Shdr
254 )
255 {
256 if (IsHiiRsrcShdr(Shdr)) {
257 return FALSE;
258 }
259 return (BOOLEAN) (Shdr->sh_flags & (SHF_WRITE | SHF_ALLOC)) == (SHF_ALLOC | SHF_WRITE);
260 }
261
262 STATIC
263 BOOLEAN
264 IsStrtabShdr (
265 Elf_Shdr *Shdr
266 )
267 {
268 Elf_Shdr *Namedr = GetShdrByIndex(mEhdr->e_shstrndx);
269
270 return (BOOLEAN) (strcmp((CHAR8*)mEhdr + Namedr->sh_offset + Shdr->sh_name, ELF_STRTAB_SECTION_NAME) == 0);
271 }
272
273 STATIC
274 Elf_Shdr *
275 FindStrtabShdr (
276 VOID
277 )
278 {
279 UINT32 i;
280 for (i = 0; i < mEhdr->e_shnum; i++) {
281 Elf_Shdr *shdr = GetShdrByIndex(i);
282 if (IsStrtabShdr(shdr)) {
283 return shdr;
284 }
285 }
286 return NULL;
287 }
288
289 STATIC
290 const UINT8 *
291 GetSymName (
292 Elf_Sym *Sym
293 )
294 {
295 if (Sym->st_name == 0) {
296 return NULL;
297 }
298
299 Elf_Shdr *StrtabShdr = FindStrtabShdr();
300 if (StrtabShdr == NULL) {
301 return NULL;
302 }
303
304 assert(Sym->st_name < StrtabShdr->sh_size);
305
306 UINT8* StrtabContents = (UINT8*)mEhdr + StrtabShdr->sh_offset;
307
308 bool foundEnd = false;
309 UINT32 i;
310 for (i= Sym->st_name; (i < StrtabShdr->sh_size) && !foundEnd; i++) {
311 foundEnd = StrtabContents[i] == 0;
312 }
313 assert(foundEnd);
314
315 return StrtabContents + Sym->st_name;
316 }
317
318 //
319 // Elf functions interface implementation
320 //
321
322 STATIC
323 VOID
324 ScanSections64 (
325 VOID
326 )
327 {
328 UINT32 i;
329 EFI_IMAGE_DOS_HEADER *DosHdr;
330 EFI_IMAGE_OPTIONAL_HEADER_UNION *NtHdr;
331 UINT32 CoffEntry;
332 UINT32 SectionCount;
333 BOOLEAN FoundSection;
334
335 CoffEntry = 0;
336 mCoffOffset = 0;
337
338 //
339 // Coff file start with a DOS header.
340 //
341 mCoffOffset = sizeof(EFI_IMAGE_DOS_HEADER) + 0x40;
342 mNtHdrOffset = mCoffOffset;
343 switch (mEhdr->e_machine) {
344 case EM_X86_64:
345 case EM_IA_64:
346 case EM_AARCH64:
347 mCoffOffset += sizeof (EFI_IMAGE_NT_HEADERS64);
348 break;
349 default:
350 VerboseMsg ("%s unknown e_machine type %hu. Assume X64", mInImageName, mEhdr->e_machine);
351 mCoffOffset += sizeof (EFI_IMAGE_NT_HEADERS64);
352 break;
353 }
354
355 mTableOffset = mCoffOffset;
356 mCoffOffset += mCoffNbrSections * sizeof(EFI_IMAGE_SECTION_HEADER);
357
358 //
359 // Set mCoffAlignment to the maximum alignment of the input sections
360 // we care about
361 //
362 for (i = 0; i < mEhdr->e_shnum; i++) {
363 Elf_Shdr *shdr = GetShdrByIndex(i);
364 if (shdr->sh_addralign <= mCoffAlignment) {
365 continue;
366 }
367 if (IsTextShdr(shdr) || IsDataShdr(shdr) || IsHiiRsrcShdr(shdr)) {
368 mCoffAlignment = (UINT32)shdr->sh_addralign;
369 }
370 }
371
372 //
373 // Move the PE/COFF header right before the first section. This will help us
374 // save space when converting to TE.
375 //
376 if (mCoffAlignment > mCoffOffset) {
377 mNtHdrOffset += mCoffAlignment - mCoffOffset;
378 mTableOffset += mCoffAlignment - mCoffOffset;
379 mCoffOffset = mCoffAlignment;
380 }
381
382 //
383 // First text sections.
384 //
385 mCoffOffset = CoffAlign(mCoffOffset);
386 mTextOffset = mCoffOffset;
387 FoundSection = FALSE;
388 SectionCount = 0;
389 for (i = 0; i < mEhdr->e_shnum; i++) {
390 Elf_Shdr *shdr = GetShdrByIndex(i);
391 if (IsTextShdr(shdr)) {
392 if ((shdr->sh_addralign != 0) && (shdr->sh_addralign != 1)) {
393 // the alignment field is valid
394 if ((shdr->sh_addr & (shdr->sh_addralign - 1)) == 0) {
395 // if the section address is aligned we must align PE/COFF
396 mCoffOffset = (UINT32) ((mCoffOffset + shdr->sh_addralign - 1) & ~(shdr->sh_addralign - 1));
397 } else {
398 Error (NULL, 0, 3000, "Invalid", "Section address not aligned to its own alignment.");
399 }
400 }
401
402 /* Relocate entry. */
403 if ((mEhdr->e_entry >= shdr->sh_addr) &&
404 (mEhdr->e_entry < shdr->sh_addr + shdr->sh_size)) {
405 CoffEntry = (UINT32) (mCoffOffset + mEhdr->e_entry - shdr->sh_addr);
406 }
407
408 //
409 // Set mTextOffset with the offset of the first '.text' section
410 //
411 if (!FoundSection) {
412 mTextOffset = mCoffOffset;
413 FoundSection = TRUE;
414 }
415
416 mCoffSectionsOffset[i] = mCoffOffset;
417 mCoffOffset += (UINT32) shdr->sh_size;
418 SectionCount ++;
419 }
420 }
421
422 if (!FoundSection) {
423 Error (NULL, 0, 3000, "Invalid", "Did not find any '.text' section.");
424 assert (FALSE);
425 }
426
427 mDebugOffset = DebugRvaAlign(mCoffOffset);
428 mCoffOffset = CoffAlign(mCoffOffset);
429
430 if (SectionCount > 1 && mOutImageType == FW_EFI_IMAGE) {
431 Warning (NULL, 0, 0, NULL, "Mulitple sections in %s are merged into 1 text section. Source level debug might not work correctly.", mInImageName);
432 }
433
434 //
435 // Then data sections.
436 //
437 mDataOffset = mCoffOffset;
438 FoundSection = FALSE;
439 SectionCount = 0;
440 for (i = 0; i < mEhdr->e_shnum; i++) {
441 Elf_Shdr *shdr = GetShdrByIndex(i);
442 if (IsDataShdr(shdr)) {
443 if ((shdr->sh_addralign != 0) && (shdr->sh_addralign != 1)) {
444 // the alignment field is valid
445 if ((shdr->sh_addr & (shdr->sh_addralign - 1)) == 0) {
446 // if the section address is aligned we must align PE/COFF
447 mCoffOffset = (UINT32) ((mCoffOffset + shdr->sh_addralign - 1) & ~(shdr->sh_addralign - 1));
448 } else {
449 Error (NULL, 0, 3000, "Invalid", "Section address not aligned to its own alignment.");
450 }
451 }
452
453 //
454 // Set mDataOffset with the offset of the first '.data' section
455 //
456 if (!FoundSection) {
457 mDataOffset = mCoffOffset;
458 FoundSection = TRUE;
459 }
460 mCoffSectionsOffset[i] = mCoffOffset;
461 mCoffOffset += (UINT32) shdr->sh_size;
462 SectionCount ++;
463 }
464 }
465
466 //
467 // Make room for .debug data in .data (or .text if .data is empty) instead of
468 // putting it in a section of its own. This is explicitly allowed by the
469 // PE/COFF spec, and prevents bloat in the binary when using large values for
470 // section alignment.
471 //
472 if (SectionCount > 0) {
473 mDebugOffset = DebugRvaAlign(mCoffOffset);
474 }
475 mCoffOffset = mDebugOffset + sizeof(EFI_IMAGE_DEBUG_DIRECTORY_ENTRY) +
476 sizeof(EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY) +
477 strlen(mInImageName) + 1;
478
479 mCoffOffset = CoffAlign(mCoffOffset);
480 if (SectionCount == 0) {
481 mDataOffset = mCoffOffset;
482 }
483
484 if (SectionCount > 1 && mOutImageType == FW_EFI_IMAGE) {
485 Warning (NULL, 0, 0, NULL, "Mulitple sections in %s are merged into 1 data section. Source level debug might not work correctly.", mInImageName);
486 }
487
488 //
489 // The HII resource sections.
490 //
491 mHiiRsrcOffset = mCoffOffset;
492 for (i = 0; i < mEhdr->e_shnum; i++) {
493 Elf_Shdr *shdr = GetShdrByIndex(i);
494 if (IsHiiRsrcShdr(shdr)) {
495 if ((shdr->sh_addralign != 0) && (shdr->sh_addralign != 1)) {
496 // the alignment field is valid
497 if ((shdr->sh_addr & (shdr->sh_addralign - 1)) == 0) {
498 // if the section address is aligned we must align PE/COFF
499 mCoffOffset = (UINT32) ((mCoffOffset + shdr->sh_addralign - 1) & ~(shdr->sh_addralign - 1));
500 } else {
501 Error (NULL, 0, 3000, "Invalid", "Section address not aligned to its own alignment.");
502 }
503 }
504 if (shdr->sh_size != 0) {
505 mHiiRsrcOffset = mCoffOffset;
506 mCoffSectionsOffset[i] = mCoffOffset;
507 mCoffOffset += (UINT32) shdr->sh_size;
508 mCoffOffset = CoffAlign(mCoffOffset);
509 SetHiiResourceHeader ((UINT8*) mEhdr + shdr->sh_offset, mHiiRsrcOffset);
510 }
511 break;
512 }
513 }
514
515 mRelocOffset = mCoffOffset;
516
517 //
518 // Allocate base Coff file. Will be expanded later for relocations.
519 //
520 mCoffFile = (UINT8 *)malloc(mCoffOffset);
521 memset(mCoffFile, 0, mCoffOffset);
522
523 //
524 // Fill headers.
525 //
526 DosHdr = (EFI_IMAGE_DOS_HEADER *)mCoffFile;
527 DosHdr->e_magic = EFI_IMAGE_DOS_SIGNATURE;
528 DosHdr->e_lfanew = mNtHdrOffset;
529
530 NtHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION*)(mCoffFile + mNtHdrOffset);
531
532 NtHdr->Pe32Plus.Signature = EFI_IMAGE_NT_SIGNATURE;
533
534 switch (mEhdr->e_machine) {
535 case EM_X86_64:
536 NtHdr->Pe32Plus.FileHeader.Machine = EFI_IMAGE_MACHINE_X64;
537 NtHdr->Pe32Plus.OptionalHeader.Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC;
538 break;
539 case EM_IA_64:
540 NtHdr->Pe32Plus.FileHeader.Machine = EFI_IMAGE_MACHINE_IPF;
541 NtHdr->Pe32Plus.OptionalHeader.Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC;
542 break;
543 case EM_AARCH64:
544 NtHdr->Pe32Plus.FileHeader.Machine = EFI_IMAGE_MACHINE_AARCH64;
545 NtHdr->Pe32Plus.OptionalHeader.Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC;
546 break;
547 default:
548 VerboseMsg ("%s unknown e_machine type. Assume X64", (UINTN)mEhdr->e_machine);
549 NtHdr->Pe32Plus.FileHeader.Machine = EFI_IMAGE_MACHINE_X64;
550 NtHdr->Pe32Plus.OptionalHeader.Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC;
551 }
552
553 NtHdr->Pe32Plus.FileHeader.NumberOfSections = mCoffNbrSections;
554 NtHdr->Pe32Plus.FileHeader.TimeDateStamp = (UINT32) time(NULL);
555 mImageTimeStamp = NtHdr->Pe32Plus.FileHeader.TimeDateStamp;
556 NtHdr->Pe32Plus.FileHeader.PointerToSymbolTable = 0;
557 NtHdr->Pe32Plus.FileHeader.NumberOfSymbols = 0;
558 NtHdr->Pe32Plus.FileHeader.SizeOfOptionalHeader = sizeof(NtHdr->Pe32Plus.OptionalHeader);
559 NtHdr->Pe32Plus.FileHeader.Characteristics = EFI_IMAGE_FILE_EXECUTABLE_IMAGE
560 | EFI_IMAGE_FILE_LINE_NUMS_STRIPPED
561 | EFI_IMAGE_FILE_LOCAL_SYMS_STRIPPED
562 | EFI_IMAGE_FILE_LARGE_ADDRESS_AWARE;
563
564 NtHdr->Pe32Plus.OptionalHeader.SizeOfCode = mDataOffset - mTextOffset;
565 NtHdr->Pe32Plus.OptionalHeader.SizeOfInitializedData = mRelocOffset - mDataOffset;
566 NtHdr->Pe32Plus.OptionalHeader.SizeOfUninitializedData = 0;
567 NtHdr->Pe32Plus.OptionalHeader.AddressOfEntryPoint = CoffEntry;
568
569 NtHdr->Pe32Plus.OptionalHeader.BaseOfCode = mTextOffset;
570
571 NtHdr->Pe32Plus.OptionalHeader.ImageBase = 0;
572 NtHdr->Pe32Plus.OptionalHeader.SectionAlignment = mCoffAlignment;
573 NtHdr->Pe32Plus.OptionalHeader.FileAlignment = mCoffAlignment;
574 NtHdr->Pe32Plus.OptionalHeader.SizeOfImage = 0;
575
576 NtHdr->Pe32Plus.OptionalHeader.SizeOfHeaders = mTextOffset;
577 NtHdr->Pe32Plus.OptionalHeader.NumberOfRvaAndSizes = EFI_IMAGE_NUMBER_OF_DIRECTORY_ENTRIES;
578
579 //
580 // Section headers.
581 //
582 if ((mDataOffset - mTextOffset) > 0) {
583 CreateSectionHeader (".text", mTextOffset, mDataOffset - mTextOffset,
584 EFI_IMAGE_SCN_CNT_CODE
585 | EFI_IMAGE_SCN_MEM_EXECUTE
586 | EFI_IMAGE_SCN_MEM_READ);
587 } else {
588 // Don't make a section of size 0.
589 NtHdr->Pe32Plus.FileHeader.NumberOfSections--;
590 }
591
592 if ((mHiiRsrcOffset - mDataOffset) > 0) {
593 CreateSectionHeader (".data", mDataOffset, mHiiRsrcOffset - mDataOffset,
594 EFI_IMAGE_SCN_CNT_INITIALIZED_DATA
595 | EFI_IMAGE_SCN_MEM_WRITE
596 | EFI_IMAGE_SCN_MEM_READ);
597 } else {
598 // Don't make a section of size 0.
599 NtHdr->Pe32Plus.FileHeader.NumberOfSections--;
600 }
601
602 if ((mRelocOffset - mHiiRsrcOffset) > 0) {
603 CreateSectionHeader (".rsrc", mHiiRsrcOffset, mRelocOffset - mHiiRsrcOffset,
604 EFI_IMAGE_SCN_CNT_INITIALIZED_DATA
605 | EFI_IMAGE_SCN_MEM_READ);
606
607 NtHdr->Pe32Plus.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE].Size = mRelocOffset - mHiiRsrcOffset;
608 NtHdr->Pe32Plus.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress = mHiiRsrcOffset;
609 } else {
610 // Don't make a section of size 0.
611 NtHdr->Pe32Plus.FileHeader.NumberOfSections--;
612 }
613
614 }
615
616 STATIC
617 BOOLEAN
618 WriteSections64 (
619 SECTION_FILTER_TYPES FilterType
620 )
621 {
622 UINT32 Idx;
623 Elf_Shdr *SecShdr;
624 UINT32 SecOffset;
625 BOOLEAN (*Filter)(Elf_Shdr *);
626
627 //
628 // Initialize filter pointer
629 //
630 switch (FilterType) {
631 case SECTION_TEXT:
632 Filter = IsTextShdr;
633 break;
634 case SECTION_HII:
635 Filter = IsHiiRsrcShdr;
636 break;
637 case SECTION_DATA:
638 Filter = IsDataShdr;
639 break;
640 default:
641 return FALSE;
642 }
643
644 //
645 // First: copy sections.
646 //
647 for (Idx = 0; Idx < mEhdr->e_shnum; Idx++) {
648 Elf_Shdr *Shdr = GetShdrByIndex(Idx);
649 if ((*Filter)(Shdr)) {
650 switch (Shdr->sh_type) {
651 case SHT_PROGBITS:
652 /* Copy. */
653 memcpy(mCoffFile + mCoffSectionsOffset[Idx],
654 (UINT8*)mEhdr + Shdr->sh_offset,
655 (size_t) Shdr->sh_size);
656 break;
657
658 case SHT_NOBITS:
659 memset(mCoffFile + mCoffSectionsOffset[Idx], 0, (size_t) Shdr->sh_size);
660 break;
661
662 default:
663 //
664 // Ignore for unkown section type.
665 //
666 VerboseMsg ("%s unknown section type %x. We directly copy this section into Coff file", mInImageName, (unsigned)Shdr->sh_type);
667 break;
668 }
669 }
670 }
671
672 //
673 // Second: apply relocations.
674 //
675 VerboseMsg ("Applying Relocations...");
676 for (Idx = 0; Idx < mEhdr->e_shnum; Idx++) {
677 //
678 // Determine if this is a relocation section.
679 //
680 Elf_Shdr *RelShdr = GetShdrByIndex(Idx);
681 if ((RelShdr->sh_type != SHT_REL) && (RelShdr->sh_type != SHT_RELA)) {
682 continue;
683 }
684
685 //
686 // If this is a ET_DYN (PIE) executable, we will encounter a dynamic SHT_RELA
687 // section that applies to the entire binary, and which will have its section
688 // index set to #0 (which is a NULL section with the SHF_ALLOC bit cleared).
689 //
690 // In the absence of GOT based relocations (which we currently don't support),
691 // this RELA section will contain redundant R_xxx_RELATIVE relocations, one
692 // for every R_xxx_xx64 relocation appearing in the per-section RELA sections.
693 // (i.e., .rela.text and .rela.data)
694 //
695 if (RelShdr->sh_info == 0) {
696 continue;
697 }
698
699 //
700 // Relocation section found. Now extract section information that the relocations
701 // apply to in the ELF data and the new COFF data.
702 //
703 SecShdr = GetShdrByIndex(RelShdr->sh_info);
704 SecOffset = mCoffSectionsOffset[RelShdr->sh_info];
705
706 //
707 // Only process relocations for the current filter type.
708 //
709 if (RelShdr->sh_type == SHT_RELA && (*Filter)(SecShdr)) {
710 UINT64 RelIdx;
711
712 //
713 // Determine the symbol table referenced by the relocation data.
714 //
715 Elf_Shdr *SymtabShdr = GetShdrByIndex(RelShdr->sh_link);
716 UINT8 *Symtab = (UINT8*)mEhdr + SymtabShdr->sh_offset;
717
718 //
719 // Process all relocation entries for this section.
720 //
721 for (RelIdx = 0; RelIdx < RelShdr->sh_size; RelIdx += (UINT32) RelShdr->sh_entsize) {
722
723 //
724 // Set pointer to relocation entry
725 //
726 Elf_Rela *Rel = (Elf_Rela *)((UINT8*)mEhdr + RelShdr->sh_offset + RelIdx);
727
728 //
729 // Set pointer to symbol table entry associated with the relocation entry.
730 //
731 Elf_Sym *Sym = (Elf_Sym *)(Symtab + ELF_R_SYM(Rel->r_info) * SymtabShdr->sh_entsize);
732
733 Elf_Shdr *SymShdr;
734 UINT8 *Targ;
735
736 //
737 // Check section header index found in symbol table and get the section
738 // header location.
739 //
740 if (Sym->st_shndx == SHN_UNDEF
741 || Sym->st_shndx >= mEhdr->e_shnum) {
742 const UINT8 *SymName = GetSymName(Sym);
743 if (SymName == NULL) {
744 SymName = (const UINT8 *)"<unknown>";
745 }
746
747 Error (NULL, 0, 3000, "Invalid",
748 "%s: Bad definition for symbol '%s'@%#llx or unsupported symbol type. "
749 "For example, absolute and undefined symbols are not supported.",
750 mInImageName, SymName, Sym->st_value);
751
752 exit(EXIT_FAILURE);
753 }
754 SymShdr = GetShdrByIndex(Sym->st_shndx);
755
756 //
757 // Convert the relocation data to a pointer into the coff file.
758 //
759 // Note:
760 // r_offset is the virtual address of the storage unit to be relocated.
761 // sh_addr is the virtual address for the base of the section.
762 //
763 // r_offset in a memory address.
764 // Convert it to a pointer in the coff file.
765 //
766 Targ = mCoffFile + SecOffset + (Rel->r_offset - SecShdr->sh_addr);
767
768 //
769 // Determine how to handle each relocation type based on the machine type.
770 //
771 if (mEhdr->e_machine == EM_X86_64) {
772 switch (ELF_R_TYPE(Rel->r_info)) {
773 case R_X86_64_NONE:
774 break;
775 case R_X86_64_64:
776 //
777 // Absolute relocation.
778 //
779 VerboseMsg ("R_X86_64_64");
780 VerboseMsg ("Offset: 0x%08X, Addend: 0x%016LX",
781 (UINT32)(SecOffset + (Rel->r_offset - SecShdr->sh_addr)),
782 *(UINT64 *)Targ);
783 *(UINT64 *)Targ = *(UINT64 *)Targ - SymShdr->sh_addr + mCoffSectionsOffset[Sym->st_shndx];
784 VerboseMsg ("Relocation: 0x%016LX", *(UINT64*)Targ);
785 break;
786 case R_X86_64_32:
787 VerboseMsg ("R_X86_64_32");
788 VerboseMsg ("Offset: 0x%08X, Addend: 0x%08X",
789 (UINT32)(SecOffset + (Rel->r_offset - SecShdr->sh_addr)),
790 *(UINT32 *)Targ);
791 *(UINT32 *)Targ = (UINT32)((UINT64)(*(UINT32 *)Targ) - SymShdr->sh_addr + mCoffSectionsOffset[Sym->st_shndx]);
792 VerboseMsg ("Relocation: 0x%08X", *(UINT32*)Targ);
793 break;
794 case R_X86_64_32S:
795 VerboseMsg ("R_X86_64_32S");
796 VerboseMsg ("Offset: 0x%08X, Addend: 0x%08X",
797 (UINT32)(SecOffset + (Rel->r_offset - SecShdr->sh_addr)),
798 *(UINT32 *)Targ);
799 *(INT32 *)Targ = (INT32)((INT64)(*(INT32 *)Targ) - SymShdr->sh_addr + mCoffSectionsOffset[Sym->st_shndx]);
800 VerboseMsg ("Relocation: 0x%08X", *(UINT32*)Targ);
801 break;
802
803 case R_X86_64_PLT32:
804 //
805 // Treat R_X86_64_PLT32 relocations as R_X86_64_PC32: this is
806 // possible since we know all code symbol references resolve to
807 // definitions in the same module (UEFI has no shared libraries),
808 // and so there is never a reason to jump via a PLT entry,
809 // allowing us to resolve the reference using the symbol directly.
810 //
811 VerboseMsg ("Treating R_X86_64_PLT32 as R_X86_64_PC32 ...");
812 /* fall through */
813 case R_X86_64_PC32:
814 //
815 // Relative relocation: Symbol - Ip + Addend
816 //
817 VerboseMsg ("R_X86_64_PC32");
818 VerboseMsg ("Offset: 0x%08X, Addend: 0x%08X",
819 (UINT32)(SecOffset + (Rel->r_offset - SecShdr->sh_addr)),
820 *(UINT32 *)Targ);
821 *(UINT32 *)Targ = (UINT32) (*(UINT32 *)Targ
822 + (mCoffSectionsOffset[Sym->st_shndx] - SymShdr->sh_addr)
823 - (SecOffset - SecShdr->sh_addr));
824 VerboseMsg ("Relocation: 0x%08X", *(UINT32 *)Targ);
825 break;
826 default:
827 Error (NULL, 0, 3000, "Invalid", "%s unsupported ELF EM_X86_64 relocation 0x%x.", mInImageName, (unsigned) ELF_R_TYPE(Rel->r_info));
828 }
829 } else if (mEhdr->e_machine == EM_AARCH64) {
830
831 switch (ELF_R_TYPE(Rel->r_info)) {
832
833 case R_AARCH64_ADR_PREL_PG_HI21:
834 //
835 // AArch64 PG_H21 relocations are typically paired with ABS_LO12
836 // relocations, where a PC-relative reference with +/- 4 GB range is
837 // split into a relative high part and an absolute low part. Since
838 // the absolute low part represents the offset into a 4 KB page, we
839 // either have to convert the ADRP into an ADR instruction, or we
840 // need to use a section alignment of at least 4 KB, so that the
841 // binary appears at a correct offset at runtime. In any case, we
842 // have to make sure that the 4 KB relative offsets of both the
843 // section containing the reference as well as the section to which
844 // it refers have not been changed during PE/COFF conversion (i.e.,
845 // in ScanSections64() above).
846 //
847 if (mCoffAlignment < 0x1000) {
848 //
849 // Attempt to convert the ADRP into an ADR instruction.
850 // This is only possible if the symbol is within +/- 1 MB.
851 //
852 INT64 Offset;
853
854 // Decode the ADRP instruction
855 Offset = (INT32)((*(UINT32 *)Targ & 0xffffe0) << 8);
856 Offset = (Offset << (6 - 5)) | ((*(UINT32 *)Targ & 0x60000000) >> (29 - 12));
857
858 //
859 // ADRP offset is relative to the previous page boundary,
860 // whereas ADR offset is relative to the instruction itself.
861 // So fix up the offset so it points to the page containing
862 // the symbol.
863 //
864 Offset -= (UINTN)(Targ - mCoffFile) & 0xfff;
865
866 if (Offset < -0x100000 || Offset > 0xfffff) {
867 Error (NULL, 0, 3000, "Invalid", "WriteSections64(): %s due to its size (> 1 MB), this module requires 4 KB section alignment.",
868 mInImageName);
869 break;
870 }
871
872 // Re-encode the offset as an ADR instruction
873 *(UINT32 *)Targ &= 0x1000001f;
874 *(UINT32 *)Targ |= ((Offset & 0x1ffffc) << (5 - 2)) | ((Offset & 0x3) << 29);
875 }
876 /* fall through */
877
878 case R_AARCH64_ADD_ABS_LO12_NC:
879 case R_AARCH64_LDST8_ABS_LO12_NC:
880 case R_AARCH64_LDST16_ABS_LO12_NC:
881 case R_AARCH64_LDST32_ABS_LO12_NC:
882 case R_AARCH64_LDST64_ABS_LO12_NC:
883 case R_AARCH64_LDST128_ABS_LO12_NC:
884 if (((SecShdr->sh_addr ^ SecOffset) & 0xfff) != 0 ||
885 ((SymShdr->sh_addr ^ mCoffSectionsOffset[Sym->st_shndx]) & 0xfff) != 0) {
886 Error (NULL, 0, 3000, "Invalid", "WriteSections64(): %s AARCH64 small code model requires identical ELF and PE/COFF section offsets modulo 4 KB.",
887 mInImageName);
888 break;
889 }
890 /* fall through */
891
892 case R_AARCH64_ADR_PREL_LO21:
893 case R_AARCH64_CONDBR19:
894 case R_AARCH64_LD_PREL_LO19:
895 case R_AARCH64_CALL26:
896 case R_AARCH64_JUMP26:
897 case R_AARCH64_PREL64:
898 case R_AARCH64_PREL32:
899 case R_AARCH64_PREL16:
900 //
901 // The GCC toolchains (i.e., binutils) may corrupt section relative
902 // relocations when emitting relocation sections into fully linked
903 // binaries. More specifically, they tend to fail to take into
904 // account the fact that a '.rodata + XXX' relocation needs to have
905 // its addend recalculated once .rodata is merged into the .text
906 // section, and the relocation emitted into the .rela.text section.
907 //
908 // We cannot really recover from this loss of information, so the
909 // only workaround is to prevent having to recalculate any relative
910 // relocations at all, by using a linker script that ensures that
911 // the offset between the Place and the Symbol is the same in both
912 // the ELF and the PE/COFF versions of the binary.
913 //
914 if ((SymShdr->sh_addr - SecShdr->sh_addr) !=
915 (mCoffSectionsOffset[Sym->st_shndx] - SecOffset)) {
916 Error (NULL, 0, 3000, "Invalid", "WriteSections64(): %s AARCH64 relative relocations require identical ELF and PE/COFF section offsets",
917 mInImageName);
918 }
919 break;
920
921 // Absolute relocations.
922 case R_AARCH64_ABS64:
923 *(UINT64 *)Targ = *(UINT64 *)Targ - SymShdr->sh_addr + mCoffSectionsOffset[Sym->st_shndx];
924 break;
925
926 default:
927 Error (NULL, 0, 3000, "Invalid", "WriteSections64(): %s unsupported ELF EM_AARCH64 relocation 0x%x.", mInImageName, (unsigned) ELF_R_TYPE(Rel->r_info));
928 }
929 } else {
930 Error (NULL, 0, 3000, "Invalid", "Not a supported machine type");
931 }
932 }
933 }
934 }
935
936 return TRUE;
937 }
938
939 STATIC
940 VOID
941 WriteRelocations64 (
942 VOID
943 )
944 {
945 UINT32 Index;
946 EFI_IMAGE_OPTIONAL_HEADER_UNION *NtHdr;
947 EFI_IMAGE_DATA_DIRECTORY *Dir;
948
949 for (Index = 0; Index < mEhdr->e_shnum; Index++) {
950 Elf_Shdr *RelShdr = GetShdrByIndex(Index);
951 if ((RelShdr->sh_type == SHT_REL) || (RelShdr->sh_type == SHT_RELA)) {
952 Elf_Shdr *SecShdr = GetShdrByIndex (RelShdr->sh_info);
953 if (IsTextShdr(SecShdr) || IsDataShdr(SecShdr)) {
954 UINT64 RelIdx;
955
956 for (RelIdx = 0; RelIdx < RelShdr->sh_size; RelIdx += RelShdr->sh_entsize) {
957 Elf_Rela *Rel = (Elf_Rela *)((UINT8*)mEhdr + RelShdr->sh_offset + RelIdx);
958
959 if (mEhdr->e_machine == EM_X86_64) {
960 switch (ELF_R_TYPE(Rel->r_info)) {
961 case R_X86_64_NONE:
962 case R_X86_64_PC32:
963 case R_X86_64_PLT32:
964 break;
965 case R_X86_64_64:
966 VerboseMsg ("EFI_IMAGE_REL_BASED_DIR64 Offset: 0x%08X",
967 mCoffSectionsOffset[RelShdr->sh_info] + (Rel->r_offset - SecShdr->sh_addr));
968 CoffAddFixup(
969 (UINT32) ((UINT64) mCoffSectionsOffset[RelShdr->sh_info]
970 + (Rel->r_offset - SecShdr->sh_addr)),
971 EFI_IMAGE_REL_BASED_DIR64);
972 break;
973 case R_X86_64_32S:
974 case R_X86_64_32:
975 VerboseMsg ("EFI_IMAGE_REL_BASED_HIGHLOW Offset: 0x%08X",
976 mCoffSectionsOffset[RelShdr->sh_info] + (Rel->r_offset - SecShdr->sh_addr));
977 CoffAddFixup(
978 (UINT32) ((UINT64) mCoffSectionsOffset[RelShdr->sh_info]
979 + (Rel->r_offset - SecShdr->sh_addr)),
980 EFI_IMAGE_REL_BASED_HIGHLOW);
981 break;
982 default:
983 Error (NULL, 0, 3000, "Invalid", "%s unsupported ELF EM_X86_64 relocation 0x%x.", mInImageName, (unsigned) ELF_R_TYPE(Rel->r_info));
984 }
985 } else if (mEhdr->e_machine == EM_AARCH64) {
986
987 switch (ELF_R_TYPE(Rel->r_info)) {
988 case R_AARCH64_ADR_PREL_LO21:
989 case R_AARCH64_CONDBR19:
990 case R_AARCH64_LD_PREL_LO19:
991 case R_AARCH64_CALL26:
992 case R_AARCH64_JUMP26:
993 case R_AARCH64_PREL64:
994 case R_AARCH64_PREL32:
995 case R_AARCH64_PREL16:
996 case R_AARCH64_ADR_PREL_PG_HI21:
997 case R_AARCH64_ADD_ABS_LO12_NC:
998 case R_AARCH64_LDST8_ABS_LO12_NC:
999 case R_AARCH64_LDST16_ABS_LO12_NC:
1000 case R_AARCH64_LDST32_ABS_LO12_NC:
1001 case R_AARCH64_LDST64_ABS_LO12_NC:
1002 case R_AARCH64_LDST128_ABS_LO12_NC:
1003 //
1004 // No fixups are required for relative relocations, provided that
1005 // the relative offsets between sections have been preserved in
1006 // the ELF to PE/COFF conversion. We have already asserted that
1007 // this is the case in WriteSections64 ().
1008 //
1009 break;
1010
1011 case R_AARCH64_ABS64:
1012 CoffAddFixup(
1013 (UINT32) ((UINT64) mCoffSectionsOffset[RelShdr->sh_info]
1014 + (Rel->r_offset - SecShdr->sh_addr)),
1015 EFI_IMAGE_REL_BASED_DIR64);
1016 break;
1017
1018 case R_AARCH64_ABS32:
1019 CoffAddFixup(
1020 (UINT32) ((UINT64) mCoffSectionsOffset[RelShdr->sh_info]
1021 + (Rel->r_offset - SecShdr->sh_addr)),
1022 EFI_IMAGE_REL_BASED_HIGHLOW);
1023 break;
1024
1025 default:
1026 Error (NULL, 0, 3000, "Invalid", "WriteRelocations64(): %s unsupported ELF EM_AARCH64 relocation 0x%x.", mInImageName, (unsigned) ELF_R_TYPE(Rel->r_info));
1027 }
1028 } else {
1029 Error (NULL, 0, 3000, "Not Supported", "This tool does not support relocations for ELF with e_machine %u (processor type).", (unsigned) mEhdr->e_machine);
1030 }
1031 }
1032 }
1033 }
1034 }
1035
1036 //
1037 // Pad by adding empty entries.
1038 //
1039 while (mCoffOffset & (mCoffAlignment - 1)) {
1040 CoffAddFixupEntry(0);
1041 }
1042
1043 NtHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)(mCoffFile + mNtHdrOffset);
1044 Dir = &NtHdr->Pe32Plus.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC];
1045 Dir->Size = mCoffOffset - mRelocOffset;
1046 if (Dir->Size == 0) {
1047 // If no relocations, null out the directory entry and don't add the .reloc section
1048 Dir->VirtualAddress = 0;
1049 NtHdr->Pe32Plus.FileHeader.NumberOfSections--;
1050 } else {
1051 Dir->VirtualAddress = mRelocOffset;
1052 CreateSectionHeader (".reloc", mRelocOffset, mCoffOffset - mRelocOffset,
1053 EFI_IMAGE_SCN_CNT_INITIALIZED_DATA
1054 | EFI_IMAGE_SCN_MEM_DISCARDABLE
1055 | EFI_IMAGE_SCN_MEM_READ);
1056 }
1057 }
1058
1059 STATIC
1060 VOID
1061 WriteDebug64 (
1062 VOID
1063 )
1064 {
1065 UINT32 Len;
1066 EFI_IMAGE_OPTIONAL_HEADER_UNION *NtHdr;
1067 EFI_IMAGE_DATA_DIRECTORY *DataDir;
1068 EFI_IMAGE_DEBUG_DIRECTORY_ENTRY *Dir;
1069 EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY *Nb10;
1070
1071 Len = strlen(mInImageName) + 1;
1072
1073 Dir = (EFI_IMAGE_DEBUG_DIRECTORY_ENTRY*)(mCoffFile + mDebugOffset);
1074 Dir->Type = EFI_IMAGE_DEBUG_TYPE_CODEVIEW;
1075 Dir->SizeOfData = sizeof(EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY) + Len;
1076 Dir->RVA = mDebugOffset + sizeof(EFI_IMAGE_DEBUG_DIRECTORY_ENTRY);
1077 Dir->FileOffset = mDebugOffset + sizeof(EFI_IMAGE_DEBUG_DIRECTORY_ENTRY);
1078
1079 Nb10 = (EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY*)(Dir + 1);
1080 Nb10->Signature = CODEVIEW_SIGNATURE_NB10;
1081 strcpy ((char *)(Nb10 + 1), mInImageName);
1082
1083
1084 NtHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)(mCoffFile + mNtHdrOffset);
1085 DataDir = &NtHdr->Pe32Plus.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG];
1086 DataDir->VirtualAddress = mDebugOffset;
1087 DataDir->Size = Dir->SizeOfData + sizeof(EFI_IMAGE_DEBUG_DIRECTORY_ENTRY);
1088 }
1089
1090 STATIC
1091 VOID
1092 SetImageSize64 (
1093 VOID
1094 )
1095 {
1096 EFI_IMAGE_OPTIONAL_HEADER_UNION *NtHdr;
1097
1098 //
1099 // Set image size
1100 //
1101 NtHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)(mCoffFile + mNtHdrOffset);
1102 NtHdr->Pe32Plus.OptionalHeader.SizeOfImage = mCoffOffset;
1103 }
1104
1105 STATIC
1106 VOID
1107 CleanUp64 (
1108 VOID
1109 )
1110 {
1111 if (mCoffSectionsOffset != NULL) {
1112 free (mCoffSectionsOffset);
1113 }
1114 }
1115
1116