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