]> git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Source/C/GenFw/Elf64Convert.c
BaseTools: Various typo
[mirror_edk2.git] / BaseTools / Source / C / GenFw / Elf64Convert.c
1 /** @file
2 Elf64 convert solution
3
4 Copyright (c) 2010 - 2018, 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 structures 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 // GOT information
99 //
100 STATIC Elf_Shdr *mGOTShdr = NULL;
101 STATIC UINT32 mGOTShindex = 0;
102 STATIC UINT32 *mGOTCoffEntries = NULL;
103 STATIC UINT32 mGOTMaxCoffEntries = 0;
104 STATIC UINT32 mGOTNumCoffEntries = 0;
105
106 //
107 // Coff information
108 //
109 STATIC UINT32 mCoffAlignment = 0x20;
110
111 //
112 // PE section alignment.
113 //
114 STATIC const UINT16 mCoffNbrSections = 4;
115
116 //
117 // ELF sections to offset in Coff file.
118 //
119 STATIC UINT32 *mCoffSectionsOffset = NULL;
120
121 //
122 // Offsets in COFF file
123 //
124 STATIC UINT32 mNtHdrOffset;
125 STATIC UINT32 mTextOffset;
126 STATIC UINT32 mDataOffset;
127 STATIC UINT32 mHiiRsrcOffset;
128 STATIC UINT32 mRelocOffset;
129 STATIC UINT32 mDebugOffset;
130
131 //
132 // Initialization Function
133 //
134 BOOLEAN
135 InitializeElf64 (
136 UINT8 *FileBuffer,
137 ELF_FUNCTION_TABLE *ElfFunctions
138 )
139 {
140 //
141 // Initialize data pointer and structures.
142 //
143 VerboseMsg ("Set EHDR");
144 mEhdr = (Elf_Ehdr*) FileBuffer;
145
146 //
147 // Check the ELF64 specific header information.
148 //
149 VerboseMsg ("Check ELF64 Header Information");
150 if (mEhdr->e_ident[EI_CLASS] != ELFCLASS64) {
151 Error (NULL, 0, 3000, "Unsupported", "ELF EI_DATA not ELFCLASS64");
152 return FALSE;
153 }
154 if (mEhdr->e_ident[EI_DATA] != ELFDATA2LSB) {
155 Error (NULL, 0, 3000, "Unsupported", "ELF EI_DATA not ELFDATA2LSB");
156 return FALSE;
157 }
158 if ((mEhdr->e_type != ET_EXEC) && (mEhdr->e_type != ET_DYN)) {
159 Error (NULL, 0, 3000, "Unsupported", "ELF e_type not ET_EXEC or ET_DYN");
160 return FALSE;
161 }
162 if (!((mEhdr->e_machine == EM_X86_64) || (mEhdr->e_machine == EM_AARCH64))) {
163 Error (NULL, 0, 3000, "Unsupported", "ELF e_machine not EM_X86_64 or EM_AARCH64");
164 return FALSE;
165 }
166 if (mEhdr->e_version != EV_CURRENT) {
167 Error (NULL, 0, 3000, "Unsupported", "ELF e_version (%u) not EV_CURRENT (%d)", (unsigned) mEhdr->e_version, EV_CURRENT);
168 return FALSE;
169 }
170
171 //
172 // Update section header pointers
173 //
174 VerboseMsg ("Update Header Pointers");
175 mShdrBase = (Elf_Shdr *)((UINT8 *)mEhdr + mEhdr->e_shoff);
176 mPhdrBase = (Elf_Phdr *)((UINT8 *)mEhdr + mEhdr->e_phoff);
177
178 //
179 // Create COFF Section offset buffer and zero.
180 //
181 VerboseMsg ("Create COFF Section Offset Buffer");
182 mCoffSectionsOffset = (UINT32 *)malloc(mEhdr->e_shnum * sizeof (UINT32));
183 if (mCoffSectionsOffset == NULL) {
184 Error (NULL, 0, 4001, "Resource", "memory cannot be allocated!");
185 return FALSE;
186 }
187 memset(mCoffSectionsOffset, 0, mEhdr->e_shnum * sizeof(UINT32));
188
189 //
190 // Fill in function pointers.
191 //
192 VerboseMsg ("Fill in Function Pointers");
193 ElfFunctions->ScanSections = ScanSections64;
194 ElfFunctions->WriteSections = WriteSections64;
195 ElfFunctions->WriteRelocations = WriteRelocations64;
196 ElfFunctions->WriteDebug = WriteDebug64;
197 ElfFunctions->SetImageSize = SetImageSize64;
198 ElfFunctions->CleanUp = CleanUp64;
199
200 return TRUE;
201 }
202
203
204 //
205 // Header by Index functions
206 //
207 STATIC
208 Elf_Shdr*
209 GetShdrByIndex (
210 UINT32 Num
211 )
212 {
213 if (Num >= mEhdr->e_shnum) {
214 Error (NULL, 0, 3000, "Invalid", "GetShdrByIndex: Index %u is too high.", Num);
215 exit(EXIT_FAILURE);
216 }
217
218 return (Elf_Shdr*)((UINT8*)mShdrBase + Num * mEhdr->e_shentsize);
219 }
220
221 STATIC
222 UINT32
223 CoffAlign (
224 UINT32 Offset
225 )
226 {
227 return (Offset + mCoffAlignment - 1) & ~(mCoffAlignment - 1);
228 }
229
230 STATIC
231 UINT32
232 DebugRvaAlign (
233 UINT32 Offset
234 )
235 {
236 return (Offset + 3) & ~3;
237 }
238
239 //
240 // filter functions
241 //
242 STATIC
243 BOOLEAN
244 IsTextShdr (
245 Elf_Shdr *Shdr
246 )
247 {
248 return (BOOLEAN) ((Shdr->sh_flags & (SHF_WRITE | SHF_ALLOC)) == SHF_ALLOC);
249 }
250
251 STATIC
252 BOOLEAN
253 IsHiiRsrcShdr (
254 Elf_Shdr *Shdr
255 )
256 {
257 Elf_Shdr *Namedr = GetShdrByIndex(mEhdr->e_shstrndx);
258
259 return (BOOLEAN) (strcmp((CHAR8*)mEhdr + Namedr->sh_offset + Shdr->sh_name, ELF_HII_SECTION_NAME) == 0);
260 }
261
262 STATIC
263 BOOLEAN
264 IsDataShdr (
265 Elf_Shdr *Shdr
266 )
267 {
268 if (IsHiiRsrcShdr(Shdr)) {
269 return FALSE;
270 }
271 return (BOOLEAN) (Shdr->sh_flags & (SHF_WRITE | SHF_ALLOC)) == (SHF_ALLOC | SHF_WRITE);
272 }
273
274 STATIC
275 BOOLEAN
276 IsStrtabShdr (
277 Elf_Shdr *Shdr
278 )
279 {
280 Elf_Shdr *Namedr = GetShdrByIndex(mEhdr->e_shstrndx);
281
282 return (BOOLEAN) (strcmp((CHAR8*)mEhdr + Namedr->sh_offset + Shdr->sh_name, ELF_STRTAB_SECTION_NAME) == 0);
283 }
284
285 STATIC
286 Elf_Shdr *
287 FindStrtabShdr (
288 VOID
289 )
290 {
291 UINT32 i;
292 for (i = 0; i < mEhdr->e_shnum; i++) {
293 Elf_Shdr *shdr = GetShdrByIndex(i);
294 if (IsStrtabShdr(shdr)) {
295 return shdr;
296 }
297 }
298 return NULL;
299 }
300
301 STATIC
302 const UINT8 *
303 GetSymName (
304 Elf_Sym *Sym
305 )
306 {
307 Elf_Shdr *StrtabShdr;
308 UINT8 *StrtabContents;
309 BOOLEAN foundEnd;
310 UINT32 i;
311
312 if (Sym->st_name == 0) {
313 return NULL;
314 }
315
316 StrtabShdr = FindStrtabShdr();
317 if (StrtabShdr == NULL) {
318 return NULL;
319 }
320
321 assert(Sym->st_name < StrtabShdr->sh_size);
322
323 StrtabContents = (UINT8*)mEhdr + StrtabShdr->sh_offset;
324
325 foundEnd = FALSE;
326 for (i= Sym->st_name; (i < StrtabShdr->sh_size) && !foundEnd; i++) {
327 foundEnd = (BOOLEAN)(StrtabContents[i] == 0);
328 }
329 assert(foundEnd);
330
331 return StrtabContents + Sym->st_name;
332 }
333
334 //
335 // Find the ELF section hosting the GOT from an ELF Rva
336 // of a single GOT entry. Normally, GOT is placed in
337 // ELF .text section, so assume once we find in which
338 // section the GOT is, all GOT entries are there, and
339 // just verify this.
340 //
341 STATIC
342 VOID
343 FindElfGOTSectionFromGOTEntryElfRva (
344 Elf64_Addr GOTEntryElfRva
345 )
346 {
347 UINT32 i;
348 if (mGOTShdr != NULL) {
349 if (GOTEntryElfRva >= mGOTShdr->sh_addr &&
350 GOTEntryElfRva < mGOTShdr->sh_addr + mGOTShdr->sh_size) {
351 return;
352 }
353 Error (NULL, 0, 3000, "Unsupported", "FindElfGOTSectionFromGOTEntryElfRva: GOT entries found in multiple sections.");
354 exit(EXIT_FAILURE);
355 }
356 for (i = 0; i < mEhdr->e_shnum; i++) {
357 Elf_Shdr *shdr = GetShdrByIndex(i);
358 if (GOTEntryElfRva >= shdr->sh_addr &&
359 GOTEntryElfRva < shdr->sh_addr + shdr->sh_size) {
360 mGOTShdr = shdr;
361 mGOTShindex = i;
362 return;
363 }
364 }
365 Error (NULL, 0, 3000, "Invalid", "FindElfGOTSectionFromGOTEntryElfRva: ElfRva 0x%016LX for GOT entry not found in any section.", GOTEntryElfRva);
366 exit(EXIT_FAILURE);
367 }
368
369 //
370 // Stores locations of GOT entries in COFF image.
371 // Returns TRUE if GOT entry is new.
372 // Simple implementation as number of GOT
373 // entries is expected to be low.
374 //
375
376 STATIC
377 BOOLEAN
378 AccumulateCoffGOTEntries (
379 UINT32 GOTCoffEntry
380 )
381 {
382 UINT32 i;
383 if (mGOTCoffEntries != NULL) {
384 for (i = 0; i < mGOTNumCoffEntries; i++) {
385 if (mGOTCoffEntries[i] == GOTCoffEntry) {
386 return FALSE;
387 }
388 }
389 }
390 if (mGOTCoffEntries == NULL) {
391 mGOTCoffEntries = (UINT32*)malloc(5 * sizeof *mGOTCoffEntries);
392 if (mGOTCoffEntries == NULL) {
393 Error (NULL, 0, 4001, "Resource", "memory cannot be allocated!");
394 }
395 assert (mGOTCoffEntries != NULL);
396 mGOTMaxCoffEntries = 5;
397 mGOTNumCoffEntries = 0;
398 } else if (mGOTNumCoffEntries == mGOTMaxCoffEntries) {
399 mGOTCoffEntries = (UINT32*)realloc(mGOTCoffEntries, 2 * mGOTMaxCoffEntries * sizeof *mGOTCoffEntries);
400 if (mGOTCoffEntries == NULL) {
401 Error (NULL, 0, 4001, "Resource", "memory cannot be allocated!");
402 }
403 assert (mGOTCoffEntries != NULL);
404 mGOTMaxCoffEntries += mGOTMaxCoffEntries;
405 }
406 mGOTCoffEntries[mGOTNumCoffEntries++] = GOTCoffEntry;
407 return TRUE;
408 }
409
410 //
411 // 32-bit Unsigned integer comparator for qsort.
412 //
413 STATIC
414 int
415 UINT32Comparator (
416 const void* lhs,
417 const void* rhs
418 )
419 {
420 if (*(const UINT32*)lhs < *(const UINT32*)rhs) {
421 return -1;
422 }
423 return *(const UINT32*)lhs > *(const UINT32*)rhs;
424 }
425
426 //
427 // Emit accumulated Coff GOT entry relocations into
428 // Coff image. This function performs its job
429 // once and then releases the entry list, so
430 // it can safely be called multiple times.
431 //
432 STATIC
433 VOID
434 EmitGOTRelocations (
435 VOID
436 )
437 {
438 UINT32 i;
439 if (mGOTCoffEntries == NULL) {
440 return;
441 }
442 //
443 // Emit Coff relocations with Rvas ordered.
444 //
445 qsort(
446 mGOTCoffEntries,
447 mGOTNumCoffEntries,
448 sizeof *mGOTCoffEntries,
449 UINT32Comparator);
450 for (i = 0; i < mGOTNumCoffEntries; i++) {
451 VerboseMsg ("EFI_IMAGE_REL_BASED_DIR64 Offset: 0x%08X", mGOTCoffEntries[i]);
452 CoffAddFixup(
453 mGOTCoffEntries[i],
454 EFI_IMAGE_REL_BASED_DIR64);
455 }
456 free(mGOTCoffEntries);
457 mGOTCoffEntries = NULL;
458 mGOTMaxCoffEntries = 0;
459 mGOTNumCoffEntries = 0;
460 }
461
462 //
463 // Elf functions interface implementation
464 //
465
466 STATIC
467 VOID
468 ScanSections64 (
469 VOID
470 )
471 {
472 UINT32 i;
473 EFI_IMAGE_DOS_HEADER *DosHdr;
474 EFI_IMAGE_OPTIONAL_HEADER_UNION *NtHdr;
475 UINT32 CoffEntry;
476 UINT32 SectionCount;
477 BOOLEAN FoundSection;
478
479 CoffEntry = 0;
480 mCoffOffset = 0;
481
482 //
483 // Coff file start with a DOS header.
484 //
485 mCoffOffset = sizeof(EFI_IMAGE_DOS_HEADER) + 0x40;
486 mNtHdrOffset = mCoffOffset;
487 switch (mEhdr->e_machine) {
488 case EM_X86_64:
489 case EM_AARCH64:
490 mCoffOffset += sizeof (EFI_IMAGE_NT_HEADERS64);
491 break;
492 default:
493 VerboseMsg ("%s unknown e_machine type %hu. Assume X64", mInImageName, mEhdr->e_machine);
494 mCoffOffset += sizeof (EFI_IMAGE_NT_HEADERS64);
495 break;
496 }
497
498 mTableOffset = mCoffOffset;
499 mCoffOffset += mCoffNbrSections * sizeof(EFI_IMAGE_SECTION_HEADER);
500
501 //
502 // Set mCoffAlignment to the maximum alignment of the input sections
503 // we care about
504 //
505 for (i = 0; i < mEhdr->e_shnum; i++) {
506 Elf_Shdr *shdr = GetShdrByIndex(i);
507 if (shdr->sh_addralign <= mCoffAlignment) {
508 continue;
509 }
510 if (IsTextShdr(shdr) || IsDataShdr(shdr) || IsHiiRsrcShdr(shdr)) {
511 mCoffAlignment = (UINT32)shdr->sh_addralign;
512 }
513 }
514
515 //
516 // Check if mCoffAlignment is larger than MAX_COFF_ALIGNMENT
517 //
518 if (mCoffAlignment > MAX_COFF_ALIGNMENT) {
519 Error (NULL, 0, 3000, "Invalid", "Section alignment is larger than MAX_COFF_ALIGNMENT.");
520 assert (FALSE);
521 }
522
523
524 //
525 // Move the PE/COFF header right before the first section. This will help us
526 // save space when converting to TE.
527 //
528 if (mCoffAlignment > mCoffOffset) {
529 mNtHdrOffset += mCoffAlignment - mCoffOffset;
530 mTableOffset += mCoffAlignment - mCoffOffset;
531 mCoffOffset = mCoffAlignment;
532 }
533
534 //
535 // First text sections.
536 //
537 mCoffOffset = CoffAlign(mCoffOffset);
538 mTextOffset = mCoffOffset;
539 FoundSection = FALSE;
540 SectionCount = 0;
541 for (i = 0; i < mEhdr->e_shnum; i++) {
542 Elf_Shdr *shdr = GetShdrByIndex(i);
543 if (IsTextShdr(shdr)) {
544 if ((shdr->sh_addralign != 0) && (shdr->sh_addralign != 1)) {
545 // the alignment field is valid
546 if ((shdr->sh_addr & (shdr->sh_addralign - 1)) == 0) {
547 // if the section address is aligned we must align PE/COFF
548 mCoffOffset = (UINT32) ((mCoffOffset + shdr->sh_addralign - 1) & ~(shdr->sh_addralign - 1));
549 } else {
550 Error (NULL, 0, 3000, "Invalid", "Section address not aligned to its own alignment.");
551 }
552 }
553
554 /* Relocate entry. */
555 if ((mEhdr->e_entry >= shdr->sh_addr) &&
556 (mEhdr->e_entry < shdr->sh_addr + shdr->sh_size)) {
557 CoffEntry = (UINT32) (mCoffOffset + mEhdr->e_entry - shdr->sh_addr);
558 }
559
560 //
561 // Set mTextOffset with the offset of the first '.text' section
562 //
563 if (!FoundSection) {
564 mTextOffset = mCoffOffset;
565 FoundSection = TRUE;
566 }
567
568 mCoffSectionsOffset[i] = mCoffOffset;
569 mCoffOffset += (UINT32) shdr->sh_size;
570 SectionCount ++;
571 }
572 }
573
574 if (!FoundSection) {
575 Error (NULL, 0, 3000, "Invalid", "Did not find any '.text' section.");
576 assert (FALSE);
577 }
578
579 mDebugOffset = DebugRvaAlign(mCoffOffset);
580 mCoffOffset = CoffAlign(mCoffOffset);
581
582 if (SectionCount > 1 && mOutImageType == FW_EFI_IMAGE) {
583 Warning (NULL, 0, 0, NULL, "Multiple sections in %s are merged into 1 text section. Source level debug might not work correctly.", mInImageName);
584 }
585
586 //
587 // Then data sections.
588 //
589 mDataOffset = mCoffOffset;
590 FoundSection = FALSE;
591 SectionCount = 0;
592 for (i = 0; i < mEhdr->e_shnum; i++) {
593 Elf_Shdr *shdr = GetShdrByIndex(i);
594 if (IsDataShdr(shdr)) {
595 if ((shdr->sh_addralign != 0) && (shdr->sh_addralign != 1)) {
596 // the alignment field is valid
597 if ((shdr->sh_addr & (shdr->sh_addralign - 1)) == 0) {
598 // if the section address is aligned we must align PE/COFF
599 mCoffOffset = (UINT32) ((mCoffOffset + shdr->sh_addralign - 1) & ~(shdr->sh_addralign - 1));
600 } else {
601 Error (NULL, 0, 3000, "Invalid", "Section address not aligned to its own alignment.");
602 }
603 }
604
605 //
606 // Set mDataOffset with the offset of the first '.data' section
607 //
608 if (!FoundSection) {
609 mDataOffset = mCoffOffset;
610 FoundSection = TRUE;
611 }
612 mCoffSectionsOffset[i] = mCoffOffset;
613 mCoffOffset += (UINT32) shdr->sh_size;
614 SectionCount ++;
615 }
616 }
617
618 //
619 // Make room for .debug data in .data (or .text if .data is empty) instead of
620 // putting it in a section of its own. This is explicitly allowed by the
621 // PE/COFF spec, and prevents bloat in the binary when using large values for
622 // section alignment.
623 //
624 if (SectionCount > 0) {
625 mDebugOffset = DebugRvaAlign(mCoffOffset);
626 }
627 mCoffOffset = mDebugOffset + sizeof(EFI_IMAGE_DEBUG_DIRECTORY_ENTRY) +
628 sizeof(EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY) +
629 strlen(mInImageName) + 1;
630
631 mCoffOffset = CoffAlign(mCoffOffset);
632 if (SectionCount == 0) {
633 mDataOffset = mCoffOffset;
634 }
635
636 if (SectionCount > 1 && mOutImageType == FW_EFI_IMAGE) {
637 Warning (NULL, 0, 0, NULL, "Multiple sections in %s are merged into 1 data section. Source level debug might not work correctly.", mInImageName);
638 }
639
640 //
641 // The HII resource sections.
642 //
643 mHiiRsrcOffset = mCoffOffset;
644 for (i = 0; i < mEhdr->e_shnum; i++) {
645 Elf_Shdr *shdr = GetShdrByIndex(i);
646 if (IsHiiRsrcShdr(shdr)) {
647 if ((shdr->sh_addralign != 0) && (shdr->sh_addralign != 1)) {
648 // the alignment field is valid
649 if ((shdr->sh_addr & (shdr->sh_addralign - 1)) == 0) {
650 // if the section address is aligned we must align PE/COFF
651 mCoffOffset = (UINT32) ((mCoffOffset + shdr->sh_addralign - 1) & ~(shdr->sh_addralign - 1));
652 } else {
653 Error (NULL, 0, 3000, "Invalid", "Section address not aligned to its own alignment.");
654 }
655 }
656 if (shdr->sh_size != 0) {
657 mHiiRsrcOffset = mCoffOffset;
658 mCoffSectionsOffset[i] = mCoffOffset;
659 mCoffOffset += (UINT32) shdr->sh_size;
660 mCoffOffset = CoffAlign(mCoffOffset);
661 SetHiiResourceHeader ((UINT8*) mEhdr + shdr->sh_offset, mHiiRsrcOffset);
662 }
663 break;
664 }
665 }
666
667 mRelocOffset = mCoffOffset;
668
669 //
670 // Allocate base Coff file. Will be expanded later for relocations.
671 //
672 mCoffFile = (UINT8 *)malloc(mCoffOffset);
673 if (mCoffFile == NULL) {
674 Error (NULL, 0, 4001, "Resource", "memory cannot be allocated!");
675 }
676 assert (mCoffFile != NULL);
677 memset(mCoffFile, 0, mCoffOffset);
678
679 //
680 // Fill headers.
681 //
682 DosHdr = (EFI_IMAGE_DOS_HEADER *)mCoffFile;
683 DosHdr->e_magic = EFI_IMAGE_DOS_SIGNATURE;
684 DosHdr->e_lfanew = mNtHdrOffset;
685
686 NtHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION*)(mCoffFile + mNtHdrOffset);
687
688 NtHdr->Pe32Plus.Signature = EFI_IMAGE_NT_SIGNATURE;
689
690 switch (mEhdr->e_machine) {
691 case EM_X86_64:
692 NtHdr->Pe32Plus.FileHeader.Machine = EFI_IMAGE_MACHINE_X64;
693 NtHdr->Pe32Plus.OptionalHeader.Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC;
694 break;
695 case EM_AARCH64:
696 NtHdr->Pe32Plus.FileHeader.Machine = EFI_IMAGE_MACHINE_AARCH64;
697 NtHdr->Pe32Plus.OptionalHeader.Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC;
698 break;
699 default:
700 VerboseMsg ("%s unknown e_machine type. Assume X64", (UINTN)mEhdr->e_machine);
701 NtHdr->Pe32Plus.FileHeader.Machine = EFI_IMAGE_MACHINE_X64;
702 NtHdr->Pe32Plus.OptionalHeader.Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC;
703 }
704
705 NtHdr->Pe32Plus.FileHeader.NumberOfSections = mCoffNbrSections;
706 NtHdr->Pe32Plus.FileHeader.TimeDateStamp = (UINT32) time(NULL);
707 mImageTimeStamp = NtHdr->Pe32Plus.FileHeader.TimeDateStamp;
708 NtHdr->Pe32Plus.FileHeader.PointerToSymbolTable = 0;
709 NtHdr->Pe32Plus.FileHeader.NumberOfSymbols = 0;
710 NtHdr->Pe32Plus.FileHeader.SizeOfOptionalHeader = sizeof(NtHdr->Pe32Plus.OptionalHeader);
711 NtHdr->Pe32Plus.FileHeader.Characteristics = EFI_IMAGE_FILE_EXECUTABLE_IMAGE
712 | EFI_IMAGE_FILE_LINE_NUMS_STRIPPED
713 | EFI_IMAGE_FILE_LOCAL_SYMS_STRIPPED
714 | EFI_IMAGE_FILE_LARGE_ADDRESS_AWARE;
715
716 NtHdr->Pe32Plus.OptionalHeader.SizeOfCode = mDataOffset - mTextOffset;
717 NtHdr->Pe32Plus.OptionalHeader.SizeOfInitializedData = mRelocOffset - mDataOffset;
718 NtHdr->Pe32Plus.OptionalHeader.SizeOfUninitializedData = 0;
719 NtHdr->Pe32Plus.OptionalHeader.AddressOfEntryPoint = CoffEntry;
720
721 NtHdr->Pe32Plus.OptionalHeader.BaseOfCode = mTextOffset;
722
723 NtHdr->Pe32Plus.OptionalHeader.ImageBase = 0;
724 NtHdr->Pe32Plus.OptionalHeader.SectionAlignment = mCoffAlignment;
725 NtHdr->Pe32Plus.OptionalHeader.FileAlignment = mCoffAlignment;
726 NtHdr->Pe32Plus.OptionalHeader.SizeOfImage = 0;
727
728 NtHdr->Pe32Plus.OptionalHeader.SizeOfHeaders = mTextOffset;
729 NtHdr->Pe32Plus.OptionalHeader.NumberOfRvaAndSizes = EFI_IMAGE_NUMBER_OF_DIRECTORY_ENTRIES;
730
731 //
732 // Section headers.
733 //
734 if ((mDataOffset - mTextOffset) > 0) {
735 CreateSectionHeader (".text", mTextOffset, mDataOffset - mTextOffset,
736 EFI_IMAGE_SCN_CNT_CODE
737 | EFI_IMAGE_SCN_MEM_EXECUTE
738 | EFI_IMAGE_SCN_MEM_READ);
739 } else {
740 // Don't make a section of size 0.
741 NtHdr->Pe32Plus.FileHeader.NumberOfSections--;
742 }
743
744 if ((mHiiRsrcOffset - mDataOffset) > 0) {
745 CreateSectionHeader (".data", mDataOffset, mHiiRsrcOffset - mDataOffset,
746 EFI_IMAGE_SCN_CNT_INITIALIZED_DATA
747 | EFI_IMAGE_SCN_MEM_WRITE
748 | EFI_IMAGE_SCN_MEM_READ);
749 } else {
750 // Don't make a section of size 0.
751 NtHdr->Pe32Plus.FileHeader.NumberOfSections--;
752 }
753
754 if ((mRelocOffset - mHiiRsrcOffset) > 0) {
755 CreateSectionHeader (".rsrc", mHiiRsrcOffset, mRelocOffset - mHiiRsrcOffset,
756 EFI_IMAGE_SCN_CNT_INITIALIZED_DATA
757 | EFI_IMAGE_SCN_MEM_READ);
758
759 NtHdr->Pe32Plus.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE].Size = mRelocOffset - mHiiRsrcOffset;
760 NtHdr->Pe32Plus.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress = mHiiRsrcOffset;
761 } else {
762 // Don't make a section of size 0.
763 NtHdr->Pe32Plus.FileHeader.NumberOfSections--;
764 }
765
766 }
767
768 STATIC
769 BOOLEAN
770 WriteSections64 (
771 SECTION_FILTER_TYPES FilterType
772 )
773 {
774 UINT32 Idx;
775 Elf_Shdr *SecShdr;
776 UINT32 SecOffset;
777 BOOLEAN (*Filter)(Elf_Shdr *);
778 Elf64_Addr GOTEntryRva;
779
780 //
781 // Initialize filter pointer
782 //
783 switch (FilterType) {
784 case SECTION_TEXT:
785 Filter = IsTextShdr;
786 break;
787 case SECTION_HII:
788 Filter = IsHiiRsrcShdr;
789 break;
790 case SECTION_DATA:
791 Filter = IsDataShdr;
792 break;
793 default:
794 return FALSE;
795 }
796
797 //
798 // First: copy sections.
799 //
800 for (Idx = 0; Idx < mEhdr->e_shnum; Idx++) {
801 Elf_Shdr *Shdr = GetShdrByIndex(Idx);
802 if ((*Filter)(Shdr)) {
803 switch (Shdr->sh_type) {
804 case SHT_PROGBITS:
805 /* Copy. */
806 if (Shdr->sh_offset + Shdr->sh_size > mFileBufferSize) {
807 return FALSE;
808 }
809 memcpy(mCoffFile + mCoffSectionsOffset[Idx],
810 (UINT8*)mEhdr + Shdr->sh_offset,
811 (size_t) Shdr->sh_size);
812 break;
813
814 case SHT_NOBITS:
815 memset(mCoffFile + mCoffSectionsOffset[Idx], 0, (size_t) Shdr->sh_size);
816 break;
817
818 default:
819 //
820 // Ignore for unknown section type.
821 //
822 VerboseMsg ("%s unknown section type %x. We ignore this unknown section type.", mInImageName, (unsigned)Shdr->sh_type);
823 break;
824 }
825 }
826 }
827
828 //
829 // Second: apply relocations.
830 //
831 VerboseMsg ("Applying Relocations...");
832 for (Idx = 0; Idx < mEhdr->e_shnum; Idx++) {
833 //
834 // Determine if this is a relocation section.
835 //
836 Elf_Shdr *RelShdr = GetShdrByIndex(Idx);
837 if ((RelShdr->sh_type != SHT_REL) && (RelShdr->sh_type != SHT_RELA)) {
838 continue;
839 }
840
841 //
842 // If this is a ET_DYN (PIE) executable, we will encounter a dynamic SHT_RELA
843 // section that applies to the entire binary, and which will have its section
844 // index set to #0 (which is a NULL section with the SHF_ALLOC bit cleared).
845 //
846 // In the absence of GOT based relocations,
847 // this RELA section will contain redundant R_xxx_RELATIVE relocations, one
848 // for every R_xxx_xx64 relocation appearing in the per-section RELA sections.
849 // (i.e., .rela.text and .rela.data)
850 //
851 if (RelShdr->sh_info == 0) {
852 continue;
853 }
854
855 //
856 // Relocation section found. Now extract section information that the relocations
857 // apply to in the ELF data and the new COFF data.
858 //
859 SecShdr = GetShdrByIndex(RelShdr->sh_info);
860 SecOffset = mCoffSectionsOffset[RelShdr->sh_info];
861
862 //
863 // Only process relocations for the current filter type.
864 //
865 if (RelShdr->sh_type == SHT_RELA && (*Filter)(SecShdr)) {
866 UINT64 RelIdx;
867
868 //
869 // Determine the symbol table referenced by the relocation data.
870 //
871 Elf_Shdr *SymtabShdr = GetShdrByIndex(RelShdr->sh_link);
872 UINT8 *Symtab = (UINT8*)mEhdr + SymtabShdr->sh_offset;
873
874 //
875 // Process all relocation entries for this section.
876 //
877 for (RelIdx = 0; RelIdx < RelShdr->sh_size; RelIdx += (UINT32) RelShdr->sh_entsize) {
878
879 //
880 // Set pointer to relocation entry
881 //
882 Elf_Rela *Rel = (Elf_Rela *)((UINT8*)mEhdr + RelShdr->sh_offset + RelIdx);
883
884 //
885 // Set pointer to symbol table entry associated with the relocation entry.
886 //
887 Elf_Sym *Sym = (Elf_Sym *)(Symtab + ELF_R_SYM(Rel->r_info) * SymtabShdr->sh_entsize);
888
889 Elf_Shdr *SymShdr;
890 UINT8 *Targ;
891
892 //
893 // Check section header index found in symbol table and get the section
894 // header location.
895 //
896 if (Sym->st_shndx == SHN_UNDEF
897 || Sym->st_shndx >= mEhdr->e_shnum) {
898 const UINT8 *SymName = GetSymName(Sym);
899 if (SymName == NULL) {
900 SymName = (const UINT8 *)"<unknown>";
901 }
902
903 Error (NULL, 0, 3000, "Invalid",
904 "%s: Bad definition for symbol '%s'@%#llx or unsupported symbol type. "
905 "For example, absolute and undefined symbols are not supported.",
906 mInImageName, SymName, Sym->st_value);
907
908 exit(EXIT_FAILURE);
909 }
910 SymShdr = GetShdrByIndex(Sym->st_shndx);
911
912 //
913 // Convert the relocation data to a pointer into the coff file.
914 //
915 // Note:
916 // r_offset is the virtual address of the storage unit to be relocated.
917 // sh_addr is the virtual address for the base of the section.
918 //
919 // r_offset in a memory address.
920 // Convert it to a pointer in the coff file.
921 //
922 Targ = mCoffFile + SecOffset + (Rel->r_offset - SecShdr->sh_addr);
923
924 //
925 // Determine how to handle each relocation type based on the machine type.
926 //
927 if (mEhdr->e_machine == EM_X86_64) {
928 switch (ELF_R_TYPE(Rel->r_info)) {
929 case R_X86_64_NONE:
930 break;
931 case R_X86_64_64:
932 //
933 // Absolute relocation.
934 //
935 VerboseMsg ("R_X86_64_64");
936 VerboseMsg ("Offset: 0x%08X, Addend: 0x%016LX",
937 (UINT32)(SecOffset + (Rel->r_offset - SecShdr->sh_addr)),
938 *(UINT64 *)Targ);
939 *(UINT64 *)Targ = *(UINT64 *)Targ - SymShdr->sh_addr + mCoffSectionsOffset[Sym->st_shndx];
940 VerboseMsg ("Relocation: 0x%016LX", *(UINT64*)Targ);
941 break;
942 case R_X86_64_32:
943 VerboseMsg ("R_X86_64_32");
944 VerboseMsg ("Offset: 0x%08X, Addend: 0x%08X",
945 (UINT32)(SecOffset + (Rel->r_offset - SecShdr->sh_addr)),
946 *(UINT32 *)Targ);
947 *(UINT32 *)Targ = (UINT32)((UINT64)(*(UINT32 *)Targ) - SymShdr->sh_addr + mCoffSectionsOffset[Sym->st_shndx]);
948 VerboseMsg ("Relocation: 0x%08X", *(UINT32*)Targ);
949 break;
950 case R_X86_64_32S:
951 VerboseMsg ("R_X86_64_32S");
952 VerboseMsg ("Offset: 0x%08X, Addend: 0x%08X",
953 (UINT32)(SecOffset + (Rel->r_offset - SecShdr->sh_addr)),
954 *(UINT32 *)Targ);
955 *(INT32 *)Targ = (INT32)((INT64)(*(INT32 *)Targ) - SymShdr->sh_addr + mCoffSectionsOffset[Sym->st_shndx]);
956 VerboseMsg ("Relocation: 0x%08X", *(UINT32*)Targ);
957 break;
958
959 case R_X86_64_PLT32:
960 //
961 // Treat R_X86_64_PLT32 relocations as R_X86_64_PC32: this is
962 // possible since we know all code symbol references resolve to
963 // definitions in the same module (UEFI has no shared libraries),
964 // and so there is never a reason to jump via a PLT entry,
965 // allowing us to resolve the reference using the symbol directly.
966 //
967 VerboseMsg ("Treating R_X86_64_PLT32 as R_X86_64_PC32 ...");
968 /* fall through */
969 case R_X86_64_PC32:
970 //
971 // Relative relocation: Symbol - Ip + Addend
972 //
973 VerboseMsg ("R_X86_64_PC32");
974 VerboseMsg ("Offset: 0x%08X, Addend: 0x%08X",
975 (UINT32)(SecOffset + (Rel->r_offset - SecShdr->sh_addr)),
976 *(UINT32 *)Targ);
977 *(UINT32 *)Targ = (UINT32) (*(UINT32 *)Targ
978 + (mCoffSectionsOffset[Sym->st_shndx] - SymShdr->sh_addr)
979 - (SecOffset - SecShdr->sh_addr));
980 VerboseMsg ("Relocation: 0x%08X", *(UINT32 *)Targ);
981 break;
982 case R_X86_64_GOTPCREL:
983 case R_X86_64_GOTPCRELX:
984 case R_X86_64_REX_GOTPCRELX:
985 VerboseMsg ("R_X86_64_GOTPCREL family");
986 VerboseMsg ("Offset: 0x%08X, Addend: 0x%08X",
987 (UINT32)(SecOffset + (Rel->r_offset - SecShdr->sh_addr)),
988 *(UINT32 *)Targ);
989 GOTEntryRva = Rel->r_offset - Rel->r_addend + *(INT32 *)Targ;
990 FindElfGOTSectionFromGOTEntryElfRva(GOTEntryRva);
991 *(UINT32 *)Targ = (UINT32) (*(UINT32 *)Targ
992 + (mCoffSectionsOffset[mGOTShindex] - mGOTShdr->sh_addr)
993 - (SecOffset - SecShdr->sh_addr));
994 VerboseMsg ("Relocation: 0x%08X", *(UINT32 *)Targ);
995 GOTEntryRva += (mCoffSectionsOffset[mGOTShindex] - mGOTShdr->sh_addr); // ELF Rva -> COFF Rva
996 if (AccumulateCoffGOTEntries((UINT32)GOTEntryRva)) {
997 //
998 // Relocate GOT entry if it's the first time we run into it
999 //
1000 Targ = mCoffFile + GOTEntryRva;
1001 //
1002 // Limitation: The following three statements assume memory
1003 // at *Targ is valid because the section containing the GOT
1004 // has already been copied from the ELF image to the Coff image.
1005 // This pre-condition presently holds because the GOT is placed
1006 // in section .text, and the ELF text sections are all copied
1007 // prior to reaching this point.
1008 // If the pre-condition is violated in the future, this fixup
1009 // either needs to be deferred after the GOT section is copied
1010 // to the Coff image, or the fixup should be performed on the
1011 // source Elf image instead of the destination Coff image.
1012 //
1013 VerboseMsg ("Offset: 0x%08X, Addend: 0x%016LX",
1014 (UINT32)GOTEntryRva,
1015 *(UINT64 *)Targ);
1016 *(UINT64 *)Targ = *(UINT64 *)Targ - SymShdr->sh_addr + mCoffSectionsOffset[Sym->st_shndx];
1017 VerboseMsg ("Relocation: 0x%016LX", *(UINT64*)Targ);
1018 }
1019 break;
1020 default:
1021 Error (NULL, 0, 3000, "Invalid", "%s unsupported ELF EM_X86_64 relocation 0x%x.", mInImageName, (unsigned) ELF_R_TYPE(Rel->r_info));
1022 }
1023 } else if (mEhdr->e_machine == EM_AARCH64) {
1024
1025 switch (ELF_R_TYPE(Rel->r_info)) {
1026
1027 case R_AARCH64_ADR_PREL_PG_HI21:
1028 //
1029 // AArch64 PG_H21 relocations are typically paired with ABS_LO12
1030 // relocations, where a PC-relative reference with +/- 4 GB range is
1031 // split into a relative high part and an absolute low part. Since
1032 // the absolute low part represents the offset into a 4 KB page, we
1033 // either have to convert the ADRP into an ADR instruction, or we
1034 // need to use a section alignment of at least 4 KB, so that the
1035 // binary appears at a correct offset at runtime. In any case, we
1036 // have to make sure that the 4 KB relative offsets of both the
1037 // section containing the reference as well as the section to which
1038 // it refers have not been changed during PE/COFF conversion (i.e.,
1039 // in ScanSections64() above).
1040 //
1041 if (mCoffAlignment < 0x1000) {
1042 //
1043 // Attempt to convert the ADRP into an ADR instruction.
1044 // This is only possible if the symbol is within +/- 1 MB.
1045 //
1046 INT64 Offset;
1047
1048 // Decode the ADRP instruction
1049 Offset = (INT32)((*(UINT32 *)Targ & 0xffffe0) << 8);
1050 Offset = (Offset << (6 - 5)) | ((*(UINT32 *)Targ & 0x60000000) >> (29 - 12));
1051
1052 //
1053 // ADRP offset is relative to the previous page boundary,
1054 // whereas ADR offset is relative to the instruction itself.
1055 // So fix up the offset so it points to the page containing
1056 // the symbol.
1057 //
1058 Offset -= (UINTN)(Targ - mCoffFile) & 0xfff;
1059
1060 if (Offset < -0x100000 || Offset > 0xfffff) {
1061 Error (NULL, 0, 3000, "Invalid", "WriteSections64(): %s due to its size (> 1 MB), this module requires 4 KB section alignment.",
1062 mInImageName);
1063 break;
1064 }
1065
1066 // Re-encode the offset as an ADR instruction
1067 *(UINT32 *)Targ &= 0x1000001f;
1068 *(UINT32 *)Targ |= ((Offset & 0x1ffffc) << (5 - 2)) | ((Offset & 0x3) << 29);
1069 }
1070 /* fall through */
1071
1072 case R_AARCH64_ADD_ABS_LO12_NC:
1073 case R_AARCH64_LDST8_ABS_LO12_NC:
1074 case R_AARCH64_LDST16_ABS_LO12_NC:
1075 case R_AARCH64_LDST32_ABS_LO12_NC:
1076 case R_AARCH64_LDST64_ABS_LO12_NC:
1077 case R_AARCH64_LDST128_ABS_LO12_NC:
1078 if (((SecShdr->sh_addr ^ SecOffset) & 0xfff) != 0 ||
1079 ((SymShdr->sh_addr ^ mCoffSectionsOffset[Sym->st_shndx]) & 0xfff) != 0) {
1080 Error (NULL, 0, 3000, "Invalid", "WriteSections64(): %s AARCH64 small code model requires identical ELF and PE/COFF section offsets modulo 4 KB.",
1081 mInImageName);
1082 break;
1083 }
1084 /* fall through */
1085
1086 case R_AARCH64_ADR_PREL_LO21:
1087 case R_AARCH64_CONDBR19:
1088 case R_AARCH64_LD_PREL_LO19:
1089 case R_AARCH64_CALL26:
1090 case R_AARCH64_JUMP26:
1091 case R_AARCH64_PREL64:
1092 case R_AARCH64_PREL32:
1093 case R_AARCH64_PREL16:
1094 //
1095 // The GCC toolchains (i.e., binutils) may corrupt section relative
1096 // relocations when emitting relocation sections into fully linked
1097 // binaries. More specifically, they tend to fail to take into
1098 // account the fact that a '.rodata + XXX' relocation needs to have
1099 // its addend recalculated once .rodata is merged into the .text
1100 // section, and the relocation emitted into the .rela.text section.
1101 //
1102 // We cannot really recover from this loss of information, so the
1103 // only workaround is to prevent having to recalculate any relative
1104 // relocations at all, by using a linker script that ensures that
1105 // the offset between the Place and the Symbol is the same in both
1106 // the ELF and the PE/COFF versions of the binary.
1107 //
1108 if ((SymShdr->sh_addr - SecShdr->sh_addr) !=
1109 (mCoffSectionsOffset[Sym->st_shndx] - SecOffset)) {
1110 Error (NULL, 0, 3000, "Invalid", "WriteSections64(): %s AARCH64 relative relocations require identical ELF and PE/COFF section offsets",
1111 mInImageName);
1112 }
1113 break;
1114
1115 // Absolute relocations.
1116 case R_AARCH64_ABS64:
1117 *(UINT64 *)Targ = *(UINT64 *)Targ - SymShdr->sh_addr + mCoffSectionsOffset[Sym->st_shndx];
1118 break;
1119
1120 default:
1121 Error (NULL, 0, 3000, "Invalid", "WriteSections64(): %s unsupported ELF EM_AARCH64 relocation 0x%x.", mInImageName, (unsigned) ELF_R_TYPE(Rel->r_info));
1122 }
1123 } else {
1124 Error (NULL, 0, 3000, "Invalid", "Not a supported machine type");
1125 }
1126 }
1127 }
1128 }
1129
1130 return TRUE;
1131 }
1132
1133 STATIC
1134 VOID
1135 WriteRelocations64 (
1136 VOID
1137 )
1138 {
1139 UINT32 Index;
1140 EFI_IMAGE_OPTIONAL_HEADER_UNION *NtHdr;
1141 EFI_IMAGE_DATA_DIRECTORY *Dir;
1142
1143 for (Index = 0; Index < mEhdr->e_shnum; Index++) {
1144 Elf_Shdr *RelShdr = GetShdrByIndex(Index);
1145 if ((RelShdr->sh_type == SHT_REL) || (RelShdr->sh_type == SHT_RELA)) {
1146 Elf_Shdr *SecShdr = GetShdrByIndex (RelShdr->sh_info);
1147 if (IsTextShdr(SecShdr) || IsDataShdr(SecShdr)) {
1148 UINT64 RelIdx;
1149
1150 for (RelIdx = 0; RelIdx < RelShdr->sh_size; RelIdx += RelShdr->sh_entsize) {
1151 Elf_Rela *Rel = (Elf_Rela *)((UINT8*)mEhdr + RelShdr->sh_offset + RelIdx);
1152
1153 if (mEhdr->e_machine == EM_X86_64) {
1154 switch (ELF_R_TYPE(Rel->r_info)) {
1155 case R_X86_64_NONE:
1156 case R_X86_64_PC32:
1157 case R_X86_64_PLT32:
1158 case R_X86_64_GOTPCREL:
1159 case R_X86_64_GOTPCRELX:
1160 case R_X86_64_REX_GOTPCRELX:
1161 break;
1162 case R_X86_64_64:
1163 VerboseMsg ("EFI_IMAGE_REL_BASED_DIR64 Offset: 0x%08X",
1164 mCoffSectionsOffset[RelShdr->sh_info] + (Rel->r_offset - SecShdr->sh_addr));
1165 CoffAddFixup(
1166 (UINT32) ((UINT64) mCoffSectionsOffset[RelShdr->sh_info]
1167 + (Rel->r_offset - SecShdr->sh_addr)),
1168 EFI_IMAGE_REL_BASED_DIR64);
1169 break;
1170 //
1171 // R_X86_64_32 and R_X86_64_32S are ELF64 relocations emitted when using
1172 // the SYSV X64 ABI small non-position-independent code model.
1173 // R_X86_64_32 is used for unsigned 32-bit immediates with a 32-bit operand
1174 // size. The value is either not extended, or zero-extended to 64 bits.
1175 // R_X86_64_32S is used for either signed 32-bit non-rip-relative displacements
1176 // or signed 32-bit immediates with a 64-bit operand size. The value is
1177 // sign-extended to 64 bits.
1178 // EFI_IMAGE_REL_BASED_HIGHLOW is a PE relocation that uses 32-bit arithmetic
1179 // for rebasing an image.
1180 // EFI PE binaries declare themselves EFI_IMAGE_FILE_LARGE_ADDRESS_AWARE and
1181 // may load above 2GB. If an EFI PE binary with a converted R_X86_64_32S
1182 // relocation is loaded above 2GB, the value will get sign-extended to the
1183 // negative part of the 64-bit address space. The negative part of the 64-bit
1184 // address space is unmapped, so accessing such an address page-faults.
1185 // In order to support R_X86_64_32S, it is necessary to unset
1186 // EFI_IMAGE_FILE_LARGE_ADDRESS_AWARE, and the EFI PE loader must implement
1187 // this flag and abstain from loading such a PE binary above 2GB.
1188 // Since this feature is not supported, support for R_X86_64_32S (and hence
1189 // the small non-position-independent code model) is disabled.
1190 //
1191 // case R_X86_64_32S:
1192 case R_X86_64_32:
1193 VerboseMsg ("EFI_IMAGE_REL_BASED_HIGHLOW Offset: 0x%08X",
1194 mCoffSectionsOffset[RelShdr->sh_info] + (Rel->r_offset - SecShdr->sh_addr));
1195 CoffAddFixup(
1196 (UINT32) ((UINT64) mCoffSectionsOffset[RelShdr->sh_info]
1197 + (Rel->r_offset - SecShdr->sh_addr)),
1198 EFI_IMAGE_REL_BASED_HIGHLOW);
1199 break;
1200 default:
1201 Error (NULL, 0, 3000, "Invalid", "%s unsupported ELF EM_X86_64 relocation 0x%x.", mInImageName, (unsigned) ELF_R_TYPE(Rel->r_info));
1202 }
1203 } else if (mEhdr->e_machine == EM_AARCH64) {
1204
1205 switch (ELF_R_TYPE(Rel->r_info)) {
1206 case R_AARCH64_ADR_PREL_LO21:
1207 case R_AARCH64_CONDBR19:
1208 case R_AARCH64_LD_PREL_LO19:
1209 case R_AARCH64_CALL26:
1210 case R_AARCH64_JUMP26:
1211 case R_AARCH64_PREL64:
1212 case R_AARCH64_PREL32:
1213 case R_AARCH64_PREL16:
1214 case R_AARCH64_ADR_PREL_PG_HI21:
1215 case R_AARCH64_ADD_ABS_LO12_NC:
1216 case R_AARCH64_LDST8_ABS_LO12_NC:
1217 case R_AARCH64_LDST16_ABS_LO12_NC:
1218 case R_AARCH64_LDST32_ABS_LO12_NC:
1219 case R_AARCH64_LDST64_ABS_LO12_NC:
1220 case R_AARCH64_LDST128_ABS_LO12_NC:
1221 //
1222 // No fixups are required for relative relocations, provided that
1223 // the relative offsets between sections have been preserved in
1224 // the ELF to PE/COFF conversion. We have already asserted that
1225 // this is the case in WriteSections64 ().
1226 //
1227 break;
1228
1229 case R_AARCH64_ABS64:
1230 CoffAddFixup(
1231 (UINT32) ((UINT64) mCoffSectionsOffset[RelShdr->sh_info]
1232 + (Rel->r_offset - SecShdr->sh_addr)),
1233 EFI_IMAGE_REL_BASED_DIR64);
1234 break;
1235
1236 case R_AARCH64_ABS32:
1237 CoffAddFixup(
1238 (UINT32) ((UINT64) mCoffSectionsOffset[RelShdr->sh_info]
1239 + (Rel->r_offset - SecShdr->sh_addr)),
1240 EFI_IMAGE_REL_BASED_HIGHLOW);
1241 break;
1242
1243 default:
1244 Error (NULL, 0, 3000, "Invalid", "WriteRelocations64(): %s unsupported ELF EM_AARCH64 relocation 0x%x.", mInImageName, (unsigned) ELF_R_TYPE(Rel->r_info));
1245 }
1246 } else {
1247 Error (NULL, 0, 3000, "Not Supported", "This tool does not support relocations for ELF with e_machine %u (processor type).", (unsigned) mEhdr->e_machine);
1248 }
1249 }
1250 if (mEhdr->e_machine == EM_X86_64 && RelShdr->sh_info == mGOTShindex) {
1251 //
1252 // Tack relocations for GOT entries after other relocations for
1253 // the section the GOT is in, as it's usually found at the end
1254 // of the section. This is done in order to maintain Rva order
1255 // of Coff relocations.
1256 //
1257 EmitGOTRelocations();
1258 }
1259 }
1260 }
1261 }
1262
1263 if (mEhdr->e_machine == EM_X86_64) {
1264 //
1265 // This is a safety net just in case the GOT is in a section
1266 // with no other relocations and the first invocation of
1267 // EmitGOTRelocations() above was skipped. This invocation
1268 // does not maintain Rva order of Coff relocations.
1269 // At present, with a single text section, all references to
1270 // the GOT and the GOT itself reside in section .text, so
1271 // if there's a GOT at all, the first invocation above
1272 // is executed.
1273 //
1274 EmitGOTRelocations();
1275 }
1276 //
1277 // Pad by adding empty entries.
1278 //
1279 while (mCoffOffset & (mCoffAlignment - 1)) {
1280 CoffAddFixupEntry(0);
1281 }
1282
1283 NtHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)(mCoffFile + mNtHdrOffset);
1284 Dir = &NtHdr->Pe32Plus.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC];
1285 Dir->Size = mCoffOffset - mRelocOffset;
1286 if (Dir->Size == 0) {
1287 // If no relocations, null out the directory entry and don't add the .reloc section
1288 Dir->VirtualAddress = 0;
1289 NtHdr->Pe32Plus.FileHeader.NumberOfSections--;
1290 } else {
1291 Dir->VirtualAddress = mRelocOffset;
1292 CreateSectionHeader (".reloc", mRelocOffset, mCoffOffset - mRelocOffset,
1293 EFI_IMAGE_SCN_CNT_INITIALIZED_DATA
1294 | EFI_IMAGE_SCN_MEM_DISCARDABLE
1295 | EFI_IMAGE_SCN_MEM_READ);
1296 }
1297 }
1298
1299 STATIC
1300 VOID
1301 WriteDebug64 (
1302 VOID
1303 )
1304 {
1305 UINT32 Len;
1306 EFI_IMAGE_OPTIONAL_HEADER_UNION *NtHdr;
1307 EFI_IMAGE_DATA_DIRECTORY *DataDir;
1308 EFI_IMAGE_DEBUG_DIRECTORY_ENTRY *Dir;
1309 EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY *Nb10;
1310
1311 Len = strlen(mInImageName) + 1;
1312
1313 Dir = (EFI_IMAGE_DEBUG_DIRECTORY_ENTRY*)(mCoffFile + mDebugOffset);
1314 Dir->Type = EFI_IMAGE_DEBUG_TYPE_CODEVIEW;
1315 Dir->SizeOfData = sizeof(EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY) + Len;
1316 Dir->RVA = mDebugOffset + sizeof(EFI_IMAGE_DEBUG_DIRECTORY_ENTRY);
1317 Dir->FileOffset = mDebugOffset + sizeof(EFI_IMAGE_DEBUG_DIRECTORY_ENTRY);
1318
1319 Nb10 = (EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY*)(Dir + 1);
1320 Nb10->Signature = CODEVIEW_SIGNATURE_NB10;
1321 strcpy ((char *)(Nb10 + 1), mInImageName);
1322
1323
1324 NtHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)(mCoffFile + mNtHdrOffset);
1325 DataDir = &NtHdr->Pe32Plus.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG];
1326 DataDir->VirtualAddress = mDebugOffset;
1327 DataDir->Size = sizeof(EFI_IMAGE_DEBUG_DIRECTORY_ENTRY);
1328 }
1329
1330 STATIC
1331 VOID
1332 SetImageSize64 (
1333 VOID
1334 )
1335 {
1336 EFI_IMAGE_OPTIONAL_HEADER_UNION *NtHdr;
1337
1338 //
1339 // Set image size
1340 //
1341 NtHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)(mCoffFile + mNtHdrOffset);
1342 NtHdr->Pe32Plus.OptionalHeader.SizeOfImage = mCoffOffset;
1343 }
1344
1345 STATIC
1346 VOID
1347 CleanUp64 (
1348 VOID
1349 )
1350 {
1351 if (mCoffSectionsOffset != NULL) {
1352 free (mCoffSectionsOffset);
1353 }
1354 }
1355
1356