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