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