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