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