]> git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Source/C/GenFw/Elf64Convert.c
MdeModulePkg:Add ESC key support in setup browser pop-up message box
[mirror_edk2.git] / BaseTools / Source / C / GenFw / Elf64Convert.c
1 /** @file
2 Elf64 convert solution
3
4 Copyright (c) 2010 - 2014, Intel Corporation. All rights reserved.<BR>
5 Portions copyright (c) 2013-2014, ARM Ltd. All rights reserved.<BR>
6
7 This program and the accompanying materials are licensed and made available
8 under the terms and conditions of the BSD License which accompanies this
9 distribution. The full text of the license may be found at
10 http://opensource.org/licenses/bsd-license.php
11
12 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
13 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
14
15 **/
16
17 #include "WinNtInclude.h"
18
19 #ifndef __GNUC__
20 #include <windows.h>
21 #include <io.h>
22 #endif
23 #include <assert.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <time.h>
28 #include <ctype.h>
29
30 #include <Common/UefiBaseTypes.h>
31 #include <IndustryStandard/PeImage.h>
32
33 #include "PeCoffLib.h"
34 #include "EfiUtilityMsgs.h"
35
36 #include "GenFw.h"
37 #include "ElfConvert.h"
38 #include "Elf64Convert.h"
39
40 STATIC
41 VOID
42 ScanSections64 (
43 VOID
44 );
45
46 STATIC
47 BOOLEAN
48 WriteSections64 (
49 SECTION_FILTER_TYPES FilterType
50 );
51
52 STATIC
53 VOID
54 WriteRelocations64 (
55 VOID
56 );
57
58 STATIC
59 VOID
60 WriteDebug64 (
61 VOID
62 );
63
64 STATIC
65 VOID
66 SetImageSize64 (
67 VOID
68 );
69
70 STATIC
71 VOID
72 CleanUp64 (
73 VOID
74 );
75
76 //
77 // Rename ELF32 strucutres to common names to help when porting to ELF64.
78 //
79 typedef Elf64_Shdr Elf_Shdr;
80 typedef Elf64_Ehdr Elf_Ehdr;
81 typedef Elf64_Rel Elf_Rel;
82 typedef Elf64_Rela Elf_Rela;
83 typedef Elf64_Sym Elf_Sym;
84 typedef Elf64_Phdr Elf_Phdr;
85 typedef Elf64_Dyn Elf_Dyn;
86 #define ELFCLASS ELFCLASS64
87 #define ELF_R_TYPE(r) ELF64_R_TYPE(r)
88 #define ELF_R_SYM(r) ELF64_R_SYM(r)
89
90 //
91 // Well known ELF structures.
92 //
93 STATIC Elf_Ehdr *mEhdr;
94 STATIC Elf_Shdr *mShdrBase;
95 STATIC Elf_Phdr *mPhdrBase;
96
97 //
98 // Coff information
99 //
100 STATIC UINT32 mCoffAlignment = 0x20;
101
102 //
103 // PE section alignment.
104 //
105 STATIC const UINT16 mCoffNbrSections = 5;
106
107 //
108 // ELF sections to offset in Coff file.
109 //
110 STATIC UINT32 *mCoffSectionsOffset = NULL;
111
112 //
113 // Offsets in COFF file
114 //
115 STATIC UINT32 mNtHdrOffset;
116 STATIC UINT32 mTextOffset;
117 STATIC UINT32 mDataOffset;
118 STATIC UINT32 mHiiRsrcOffset;
119 STATIC UINT32 mRelocOffset;
120
121 //
122 // Initialization Function
123 //
124 BOOLEAN
125 InitializeElf64 (
126 UINT8 *FileBuffer,
127 ELF_FUNCTION_TABLE *ElfFunctions
128 )
129 {
130 //
131 // Initialize data pointer and structures.
132 //
133 VerboseMsg ("Set EHDR");
134 mEhdr = (Elf_Ehdr*) FileBuffer;
135
136 //
137 // Check the ELF64 specific header information.
138 //
139 VerboseMsg ("Check ELF64 Header Information");
140 if (mEhdr->e_ident[EI_CLASS] != ELFCLASS64) {
141 Error (NULL, 0, 3000, "Unsupported", "ELF EI_DATA not ELFCLASS64");
142 return FALSE;
143 }
144 if (mEhdr->e_ident[EI_DATA] != ELFDATA2LSB) {
145 Error (NULL, 0, 3000, "Unsupported", "ELF EI_DATA not ELFDATA2LSB");
146 return FALSE;
147 }
148 if ((mEhdr->e_type != ET_EXEC) && (mEhdr->e_type != ET_DYN)) {
149 Error (NULL, 0, 3000, "Unsupported", "ELF e_type not ET_EXEC or ET_DYN");
150 return FALSE;
151 }
152 if (!((mEhdr->e_machine == EM_X86_64) || (mEhdr->e_machine == EM_AARCH64))) {
153 Error (NULL, 0, 3000, "Unsupported", "ELF e_machine not EM_X86_64 or EM_AARCH64");
154 return FALSE;
155 }
156 if (mEhdr->e_version != EV_CURRENT) {
157 Error (NULL, 0, 3000, "Unsupported", "ELF e_version (%u) not EV_CURRENT (%d)", (unsigned) mEhdr->e_version, EV_CURRENT);
158 return FALSE;
159 }
160
161 //
162 // Update section header pointers
163 //
164 VerboseMsg ("Update Header Pointers");
165 mShdrBase = (Elf_Shdr *)((UINT8 *)mEhdr + mEhdr->e_shoff);
166 mPhdrBase = (Elf_Phdr *)((UINT8 *)mEhdr + mEhdr->e_phoff);
167
168 //
169 // Create COFF Section offset buffer and zero.
170 //
171 VerboseMsg ("Create COFF Section Offset Buffer");
172 mCoffSectionsOffset = (UINT32 *)malloc(mEhdr->e_shnum * sizeof (UINT32));
173 memset(mCoffSectionsOffset, 0, mEhdr->e_shnum * sizeof(UINT32));
174
175 //
176 // Fill in function pointers.
177 //
178 VerboseMsg ("Fill in Function Pointers");
179 ElfFunctions->ScanSections = ScanSections64;
180 ElfFunctions->WriteSections = WriteSections64;
181 ElfFunctions->WriteRelocations = WriteRelocations64;
182 ElfFunctions->WriteDebug = WriteDebug64;
183 ElfFunctions->SetImageSize = SetImageSize64;
184 ElfFunctions->CleanUp = CleanUp64;
185
186 return TRUE;
187 }
188
189
190 //
191 // Header by Index functions
192 //
193 STATIC
194 Elf_Shdr*
195 GetShdrByIndex (
196 UINT32 Num
197 )
198 {
199 if (Num >= mEhdr->e_shnum)
200 return NULL;
201 return (Elf_Shdr*)((UINT8*)mShdrBase + Num * mEhdr->e_shentsize);
202 }
203
204 STATIC
205 UINT32
206 CoffAlign (
207 UINT32 Offset
208 )
209 {
210 return (Offset + mCoffAlignment - 1) & ~(mCoffAlignment - 1);
211 }
212
213 //
214 // filter functions
215 //
216 STATIC
217 BOOLEAN
218 IsTextShdr (
219 Elf_Shdr *Shdr
220 )
221 {
222 return (BOOLEAN) ((Shdr->sh_flags & (SHF_WRITE | SHF_ALLOC)) == SHF_ALLOC);
223 }
224
225 STATIC
226 BOOLEAN
227 IsHiiRsrcShdr (
228 Elf_Shdr *Shdr
229 )
230 {
231 Elf_Shdr *Namedr = GetShdrByIndex(mEhdr->e_shstrndx);
232
233 return (BOOLEAN) (strcmp((CHAR8*)mEhdr + Namedr->sh_offset + Shdr->sh_name, ELF_HII_SECTION_NAME) == 0);
234 }
235
236 STATIC
237 BOOLEAN
238 IsDataShdr (
239 Elf_Shdr *Shdr
240 )
241 {
242 if (IsHiiRsrcShdr(Shdr)) {
243 return FALSE;
244 }
245 return (BOOLEAN) (Shdr->sh_flags & (SHF_WRITE | SHF_ALLOC)) == (SHF_ALLOC | SHF_WRITE);
246 }
247
248 //
249 // Elf functions interface implementation
250 //
251
252 STATIC
253 VOID
254 ScanSections64 (
255 VOID
256 )
257 {
258 UINT32 i;
259 EFI_IMAGE_DOS_HEADER *DosHdr;
260 EFI_IMAGE_OPTIONAL_HEADER_UNION *NtHdr;
261 UINT32 CoffEntry;
262 UINT32 SectionCount;
263 BOOLEAN FoundSection;
264
265 CoffEntry = 0;
266 mCoffOffset = 0;
267
268 //
269 // Coff file start with a DOS header.
270 //
271 mCoffOffset = sizeof(EFI_IMAGE_DOS_HEADER) + 0x40;
272 mNtHdrOffset = mCoffOffset;
273 switch (mEhdr->e_machine) {
274 case EM_X86_64:
275 case EM_IA_64:
276 case EM_AARCH64:
277 mCoffOffset += sizeof (EFI_IMAGE_NT_HEADERS64);
278 break;
279 default:
280 VerboseMsg ("%s unknown e_machine type. Assume X64", (UINTN)mEhdr->e_machine);
281 mCoffOffset += sizeof (EFI_IMAGE_NT_HEADERS64);
282 break;
283 }
284
285 mTableOffset = mCoffOffset;
286 mCoffOffset += mCoffNbrSections * sizeof(EFI_IMAGE_SECTION_HEADER);
287
288 //
289 // Set mCoffAlignment to the maximum alignment of the input sections
290 // we care about
291 //
292 for (i = 0; i < mEhdr->e_shnum; i++) {
293 Elf_Shdr *shdr = GetShdrByIndex(i);
294 if (shdr->sh_addralign <= mCoffAlignment) {
295 continue;
296 }
297 if (IsTextShdr(shdr) || IsDataShdr(shdr) || IsHiiRsrcShdr(shdr)) {
298 mCoffAlignment = (UINT32)shdr->sh_addralign;
299 }
300 }
301
302 //
303 // First text sections.
304 //
305 mCoffOffset = CoffAlign(mCoffOffset);
306 mTextOffset = mCoffOffset;
307 FoundSection = FALSE;
308 SectionCount = 0;
309 for (i = 0; i < mEhdr->e_shnum; i++) {
310 Elf_Shdr *shdr = GetShdrByIndex(i);
311 if (IsTextShdr(shdr)) {
312 if ((shdr->sh_addralign != 0) && (shdr->sh_addralign != 1)) {
313 // the alignment field is valid
314 if ((shdr->sh_addr & (shdr->sh_addralign - 1)) == 0) {
315 // if the section address is aligned we must align PE/COFF
316 mCoffOffset = (UINT32) ((mCoffOffset + shdr->sh_addralign - 1) & ~(shdr->sh_addralign - 1));
317 } else if ((shdr->sh_addr % shdr->sh_addralign) != (mCoffOffset % shdr->sh_addralign)) {
318 // ARM RVCT tools have behavior outside of the ELF specification to try
319 // and make images smaller. If sh_addr is not aligned to sh_addralign
320 // then the section needs to preserve sh_addr MOD sh_addralign.
321 // Normally doing nothing here works great.
322 Error (NULL, 0, 3000, "Invalid", "Unsupported section alignment.");
323 }
324 }
325
326 /* Relocate entry. */
327 if ((mEhdr->e_entry >= shdr->sh_addr) &&
328 (mEhdr->e_entry < shdr->sh_addr + shdr->sh_size)) {
329 CoffEntry = (UINT32) (mCoffOffset + mEhdr->e_entry - shdr->sh_addr);
330 }
331
332 //
333 // Set mTextOffset with the offset of the first '.text' section
334 //
335 if (!FoundSection) {
336 mTextOffset = mCoffOffset;
337 FoundSection = TRUE;
338 }
339
340 mCoffSectionsOffset[i] = mCoffOffset;
341 mCoffOffset += (UINT32) shdr->sh_size;
342 SectionCount ++;
343 }
344 }
345
346 if (!FoundSection) {
347 Error (NULL, 0, 3000, "Invalid", "Did not find any '.text' section.");
348 assert (FALSE);
349 }
350
351 if (mEhdr->e_machine != EM_ARM) {
352 mCoffOffset = CoffAlign(mCoffOffset);
353 }
354
355 if (SectionCount > 1 && mOutImageType == FW_EFI_IMAGE) {
356 Warning (NULL, 0, 0, NULL, "Mulitple sections in %s are merged into 1 text section. Source level debug might not work correctly.", mInImageName);
357 }
358
359 //
360 // Then data sections.
361 //
362 mDataOffset = mCoffOffset;
363 FoundSection = FALSE;
364 SectionCount = 0;
365 for (i = 0; i < mEhdr->e_shnum; i++) {
366 Elf_Shdr *shdr = GetShdrByIndex(i);
367 if (IsDataShdr(shdr)) {
368 if ((shdr->sh_addralign != 0) && (shdr->sh_addralign != 1)) {
369 // the alignment field is valid
370 if ((shdr->sh_addr & (shdr->sh_addralign - 1)) == 0) {
371 // if the section address is aligned we must align PE/COFF
372 mCoffOffset = (UINT32) ((mCoffOffset + shdr->sh_addralign - 1) & ~(shdr->sh_addralign - 1));
373 } else if ((shdr->sh_addr % shdr->sh_addralign) != (mCoffOffset % shdr->sh_addralign)) {
374 // ARM RVCT tools have behavior outside of the ELF specification to try
375 // and make images smaller. If sh_addr is not aligned to sh_addralign
376 // then the section needs to preserve sh_addr MOD sh_addralign.
377 // Normally doing nothing here works great.
378 Error (NULL, 0, 3000, "Invalid", "Unsupported section alignment.");
379 }
380 }
381
382 //
383 // Set mDataOffset with the offset of the first '.data' section
384 //
385 if (!FoundSection) {
386 mDataOffset = mCoffOffset;
387 FoundSection = TRUE;
388 }
389 mCoffSectionsOffset[i] = mCoffOffset;
390 mCoffOffset += (UINT32) shdr->sh_size;
391 SectionCount ++;
392 }
393 }
394 mCoffOffset = CoffAlign(mCoffOffset);
395
396 if (SectionCount > 1 && mOutImageType == FW_EFI_IMAGE) {
397 Warning (NULL, 0, 0, NULL, "Mulitple sections in %s are merged into 1 data section. Source level debug might not work correctly.", mInImageName);
398 }
399
400 //
401 // The HII resource sections.
402 //
403 mHiiRsrcOffset = mCoffOffset;
404 for (i = 0; i < mEhdr->e_shnum; i++) {
405 Elf_Shdr *shdr = GetShdrByIndex(i);
406 if (IsHiiRsrcShdr(shdr)) {
407 if ((shdr->sh_addralign != 0) && (shdr->sh_addralign != 1)) {
408 // the alignment field is valid
409 if ((shdr->sh_addr & (shdr->sh_addralign - 1)) == 0) {
410 // if the section address is aligned we must align PE/COFF
411 mCoffOffset = (UINT32) ((mCoffOffset + shdr->sh_addralign - 1) & ~(shdr->sh_addralign - 1));
412 } else if ((shdr->sh_addr % shdr->sh_addralign) != (mCoffOffset % shdr->sh_addralign)) {
413 // ARM RVCT tools have behavior outside of the ELF specification to try
414 // and make images smaller. If sh_addr is not aligned to sh_addralign
415 // then the section needs to preserve sh_addr MOD sh_addralign.
416 // Normally doing nothing here works great.
417 Error (NULL, 0, 3000, "Invalid", "Unsupported section alignment.");
418 }
419 }
420 if (shdr->sh_size != 0) {
421 mHiiRsrcOffset = mCoffOffset;
422 mCoffSectionsOffset[i] = mCoffOffset;
423 mCoffOffset += (UINT32) shdr->sh_size;
424 mCoffOffset = CoffAlign(mCoffOffset);
425 SetHiiResourceHeader ((UINT8*) mEhdr + shdr->sh_offset, mHiiRsrcOffset);
426 }
427 break;
428 }
429 }
430
431 mRelocOffset = mCoffOffset;
432
433 //
434 // Allocate base Coff file. Will be expanded later for relocations.
435 //
436 mCoffFile = (UINT8 *)malloc(mCoffOffset);
437 memset(mCoffFile, 0, mCoffOffset);
438
439 //
440 // Fill headers.
441 //
442 DosHdr = (EFI_IMAGE_DOS_HEADER *)mCoffFile;
443 DosHdr->e_magic = EFI_IMAGE_DOS_SIGNATURE;
444 DosHdr->e_lfanew = mNtHdrOffset;
445
446 NtHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION*)(mCoffFile + mNtHdrOffset);
447
448 NtHdr->Pe32Plus.Signature = EFI_IMAGE_NT_SIGNATURE;
449
450 switch (mEhdr->e_machine) {
451 case EM_X86_64:
452 NtHdr->Pe32Plus.FileHeader.Machine = EFI_IMAGE_MACHINE_X64;
453 NtHdr->Pe32Plus.OptionalHeader.Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC;
454 break;
455 case EM_IA_64:
456 NtHdr->Pe32Plus.FileHeader.Machine = EFI_IMAGE_MACHINE_IPF;
457 NtHdr->Pe32Plus.OptionalHeader.Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC;
458 break;
459 case EM_AARCH64:
460 NtHdr->Pe32Plus.FileHeader.Machine = EFI_IMAGE_MACHINE_AARCH64;
461 NtHdr->Pe32Plus.OptionalHeader.Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC;
462 break;
463 default:
464 VerboseMsg ("%s unknown e_machine type. Assume X64", (UINTN)mEhdr->e_machine);
465 NtHdr->Pe32Plus.FileHeader.Machine = EFI_IMAGE_MACHINE_X64;
466 NtHdr->Pe32Plus.OptionalHeader.Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC;
467 }
468
469 NtHdr->Pe32Plus.FileHeader.NumberOfSections = mCoffNbrSections;
470 NtHdr->Pe32Plus.FileHeader.TimeDateStamp = (UINT32) time(NULL);
471 mImageTimeStamp = NtHdr->Pe32Plus.FileHeader.TimeDateStamp;
472 NtHdr->Pe32Plus.FileHeader.PointerToSymbolTable = 0;
473 NtHdr->Pe32Plus.FileHeader.NumberOfSymbols = 0;
474 NtHdr->Pe32Plus.FileHeader.SizeOfOptionalHeader = sizeof(NtHdr->Pe32Plus.OptionalHeader);
475 NtHdr->Pe32Plus.FileHeader.Characteristics = EFI_IMAGE_FILE_EXECUTABLE_IMAGE
476 | EFI_IMAGE_FILE_LINE_NUMS_STRIPPED
477 | EFI_IMAGE_FILE_LOCAL_SYMS_STRIPPED
478 | EFI_IMAGE_FILE_LARGE_ADDRESS_AWARE;
479
480 NtHdr->Pe32Plus.OptionalHeader.SizeOfCode = mDataOffset - mTextOffset;
481 NtHdr->Pe32Plus.OptionalHeader.SizeOfInitializedData = mRelocOffset - mDataOffset;
482 NtHdr->Pe32Plus.OptionalHeader.SizeOfUninitializedData = 0;
483 NtHdr->Pe32Plus.OptionalHeader.AddressOfEntryPoint = CoffEntry;
484
485 NtHdr->Pe32Plus.OptionalHeader.BaseOfCode = mTextOffset;
486
487 NtHdr->Pe32Plus.OptionalHeader.ImageBase = 0;
488 NtHdr->Pe32Plus.OptionalHeader.SectionAlignment = mCoffAlignment;
489 NtHdr->Pe32Plus.OptionalHeader.FileAlignment = mCoffAlignment;
490 NtHdr->Pe32Plus.OptionalHeader.SizeOfImage = 0;
491
492 NtHdr->Pe32Plus.OptionalHeader.SizeOfHeaders = mTextOffset;
493 NtHdr->Pe32Plus.OptionalHeader.NumberOfRvaAndSizes = EFI_IMAGE_NUMBER_OF_DIRECTORY_ENTRIES;
494
495 //
496 // Section headers.
497 //
498 if ((mDataOffset - mTextOffset) > 0) {
499 CreateSectionHeader (".text", mTextOffset, mDataOffset - mTextOffset,
500 EFI_IMAGE_SCN_CNT_CODE
501 | EFI_IMAGE_SCN_MEM_EXECUTE
502 | EFI_IMAGE_SCN_MEM_READ);
503 } else {
504 // Don't make a section of size 0.
505 NtHdr->Pe32Plus.FileHeader.NumberOfSections--;
506 }
507
508 if ((mHiiRsrcOffset - mDataOffset) > 0) {
509 CreateSectionHeader (".data", mDataOffset, mHiiRsrcOffset - mDataOffset,
510 EFI_IMAGE_SCN_CNT_INITIALIZED_DATA
511 | EFI_IMAGE_SCN_MEM_WRITE
512 | EFI_IMAGE_SCN_MEM_READ);
513 } else {
514 // Don't make a section of size 0.
515 NtHdr->Pe32Plus.FileHeader.NumberOfSections--;
516 }
517
518 if ((mRelocOffset - mHiiRsrcOffset) > 0) {
519 CreateSectionHeader (".rsrc", mHiiRsrcOffset, mRelocOffset - mHiiRsrcOffset,
520 EFI_IMAGE_SCN_CNT_INITIALIZED_DATA
521 | EFI_IMAGE_SCN_MEM_READ);
522
523 NtHdr->Pe32Plus.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE].Size = mRelocOffset - mHiiRsrcOffset;
524 NtHdr->Pe32Plus.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress = mHiiRsrcOffset;
525 } else {
526 // Don't make a section of size 0.
527 NtHdr->Pe32Plus.FileHeader.NumberOfSections--;
528 }
529
530 }
531
532 STATIC
533 BOOLEAN
534 WriteSections64 (
535 SECTION_FILTER_TYPES FilterType
536 )
537 {
538 UINT32 Idx;
539 Elf_Shdr *SecShdr;
540 UINT32 SecOffset;
541 BOOLEAN (*Filter)(Elf_Shdr *);
542
543 //
544 // Initialize filter pointer
545 //
546 switch (FilterType) {
547 case SECTION_TEXT:
548 Filter = IsTextShdr;
549 break;
550 case SECTION_HII:
551 Filter = IsHiiRsrcShdr;
552 break;
553 case SECTION_DATA:
554 Filter = IsDataShdr;
555 break;
556 default:
557 return FALSE;
558 }
559
560 //
561 // First: copy sections.
562 //
563 for (Idx = 0; Idx < mEhdr->e_shnum; Idx++) {
564 Elf_Shdr *Shdr = GetShdrByIndex(Idx);
565 if ((*Filter)(Shdr)) {
566 switch (Shdr->sh_type) {
567 case SHT_PROGBITS:
568 /* Copy. */
569 memcpy(mCoffFile + mCoffSectionsOffset[Idx],
570 (UINT8*)mEhdr + Shdr->sh_offset,
571 (size_t) Shdr->sh_size);
572 break;
573
574 case SHT_NOBITS:
575 memset(mCoffFile + mCoffSectionsOffset[Idx], 0, (size_t) Shdr->sh_size);
576 break;
577
578 default:
579 //
580 // Ignore for unkown section type.
581 //
582 VerboseMsg ("%s unknown section type %x. We directly copy this section into Coff file", mInImageName, (unsigned)Shdr->sh_type);
583 break;
584 }
585 }
586 }
587
588 //
589 // Second: apply relocations.
590 //
591 VerboseMsg ("Applying Relocations...");
592 for (Idx = 0; Idx < mEhdr->e_shnum; Idx++) {
593 //
594 // Determine if this is a relocation section.
595 //
596 Elf_Shdr *RelShdr = GetShdrByIndex(Idx);
597 if ((RelShdr->sh_type != SHT_REL) && (RelShdr->sh_type != SHT_RELA)) {
598 continue;
599 }
600
601 //
602 // Relocation section found. Now extract section information that the relocations
603 // apply to in the ELF data and the new COFF data.
604 //
605 SecShdr = GetShdrByIndex(RelShdr->sh_info);
606 SecOffset = mCoffSectionsOffset[RelShdr->sh_info];
607
608 //
609 // Only process relocations for the current filter type.
610 //
611 if (RelShdr->sh_type == SHT_RELA && (*Filter)(SecShdr)) {
612 UINT64 RelIdx;
613
614 //
615 // Determine the symbol table referenced by the relocation data.
616 //
617 Elf_Shdr *SymtabShdr = GetShdrByIndex(RelShdr->sh_link);
618 UINT8 *Symtab = (UINT8*)mEhdr + SymtabShdr->sh_offset;
619
620 //
621 // Process all relocation entries for this section.
622 //
623 for (RelIdx = 0; RelIdx < RelShdr->sh_size; RelIdx += (UINT32) RelShdr->sh_entsize) {
624
625 //
626 // Set pointer to relocation entry
627 //
628 Elf_Rela *Rel = (Elf_Rela *)((UINT8*)mEhdr + RelShdr->sh_offset + RelIdx);
629
630 //
631 // Set pointer to symbol table entry associated with the relocation entry.
632 //
633 Elf_Sym *Sym = (Elf_Sym *)(Symtab + ELF_R_SYM(Rel->r_info) * SymtabShdr->sh_entsize);
634
635 Elf_Shdr *SymShdr;
636 UINT8 *Targ;
637
638 //
639 // Check section header index found in symbol table and get the section
640 // header location.
641 //
642 if (Sym->st_shndx == SHN_UNDEF
643 || Sym->st_shndx == SHN_ABS
644 || Sym->st_shndx > mEhdr->e_shnum) {
645 Error (NULL, 0, 3000, "Invalid", "%s bad symbol definition.", mInImageName);
646 }
647 SymShdr = GetShdrByIndex(Sym->st_shndx);
648
649 //
650 // Convert the relocation data to a pointer into the coff file.
651 //
652 // Note:
653 // r_offset is the virtual address of the storage unit to be relocated.
654 // sh_addr is the virtual address for the base of the section.
655 //
656 // r_offset in a memory address.
657 // Convert it to a pointer in the coff file.
658 //
659 Targ = mCoffFile + SecOffset + (Rel->r_offset - SecShdr->sh_addr);
660
661 //
662 // Determine how to handle each relocation type based on the machine type.
663 //
664 if (mEhdr->e_machine == EM_X86_64) {
665 switch (ELF_R_TYPE(Rel->r_info)) {
666 case R_X86_64_NONE:
667 break;
668 case R_X86_64_64:
669 //
670 // Absolute relocation.
671 //
672 VerboseMsg ("R_X86_64_64");
673 VerboseMsg ("Offset: 0x%08X, Addend: 0x%016LX",
674 (UINT32)(SecOffset + (Rel->r_offset - SecShdr->sh_addr)),
675 *(UINT64 *)Targ);
676 *(UINT64 *)Targ = *(UINT64 *)Targ - SymShdr->sh_addr + mCoffSectionsOffset[Sym->st_shndx];
677 VerboseMsg ("Relocation: 0x%016LX", *(UINT64*)Targ);
678 break;
679 case R_X86_64_32:
680 VerboseMsg ("R_X86_64_32");
681 VerboseMsg ("Offset: 0x%08X, Addend: 0x%08X",
682 (UINT32)(SecOffset + (Rel->r_offset - SecShdr->sh_addr)),
683 *(UINT32 *)Targ);
684 *(UINT32 *)Targ = (UINT32)((UINT64)(*(UINT32 *)Targ) - SymShdr->sh_addr + mCoffSectionsOffset[Sym->st_shndx]);
685 VerboseMsg ("Relocation: 0x%08X", *(UINT32*)Targ);
686 break;
687 case R_X86_64_32S:
688 VerboseMsg ("R_X86_64_32S");
689 VerboseMsg ("Offset: 0x%08X, Addend: 0x%08X",
690 (UINT32)(SecOffset + (Rel->r_offset - SecShdr->sh_addr)),
691 *(UINT32 *)Targ);
692 *(INT32 *)Targ = (INT32)((INT64)(*(INT32 *)Targ) - SymShdr->sh_addr + mCoffSectionsOffset[Sym->st_shndx]);
693 VerboseMsg ("Relocation: 0x%08X", *(UINT32*)Targ);
694 break;
695 case R_X86_64_PC32:
696 //
697 // Relative relocation: Symbol - Ip + Addend
698 //
699 VerboseMsg ("R_X86_64_PC32");
700 VerboseMsg ("Offset: 0x%08X, Addend: 0x%08X",
701 (UINT32)(SecOffset + (Rel->r_offset - SecShdr->sh_addr)),
702 *(UINT32 *)Targ);
703 *(UINT32 *)Targ = (UINT32) (*(UINT32 *)Targ
704 + (mCoffSectionsOffset[Sym->st_shndx] - SymShdr->sh_addr)
705 - (SecOffset - SecShdr->sh_addr));
706 VerboseMsg ("Relocation: 0x%08X", *(UINT32 *)Targ);
707 break;
708 default:
709 Error (NULL, 0, 3000, "Invalid", "%s unsupported ELF EM_X86_64 relocation 0x%x.", mInImageName, (unsigned) ELF_R_TYPE(Rel->r_info));
710 }
711 } else if (mEhdr->e_machine == EM_AARCH64) {
712
713 // AARCH64 GCC uses RELA relocation, so all relocations have to be fixed up.
714 // As opposed to ARM32 using REL.
715
716 switch (ELF_R_TYPE(Rel->r_info)) {
717
718 case R_AARCH64_ADR_PREL_LO21:
719 if (Rel->r_addend != 0 ) { /* TODO */
720 Error (NULL, 0, 3000, "Invalid", "AArch64: R_AARCH64_ADR_PREL_LO21 Need to fixup with addend!.");
721 }
722 break;
723
724 case R_AARCH64_CONDBR19:
725 if (Rel->r_addend != 0 ) { /* TODO */
726 Error (NULL, 0, 3000, "Invalid", "AArch64: R_AARCH64_CONDBR19 Need to fixup with addend!.");
727 }
728 break;
729
730 case R_AARCH64_LD_PREL_LO19:
731 if (Rel->r_addend != 0 ) { /* TODO */
732 Error (NULL, 0, 3000, "Invalid", "AArch64: R_AARCH64_LD_PREL_LO19 Need to fixup with addend!.");
733 }
734 break;
735
736 case R_AARCH64_CALL26:
737 case R_AARCH64_JUMP26:
738 if (Rel->r_addend != 0 ) {
739 // Some references to static functions sometime start at the base of .text + addend.
740 // It is safe to ignore these relocations because they patch a `BL` instructions that
741 // contains an offset from the instruction itself and there is only a single .text section.
742 // So we check if the symbol is a "section symbol"
743 if (ELF64_ST_TYPE (Sym->st_info) == STT_SECTION) {
744 break;
745 }
746 Error (NULL, 0, 3000, "Invalid", "AArch64: R_AARCH64_JUMP26 Need to fixup with addend!.");
747 }
748 break;
749
750 case R_AARCH64_ADR_PREL_PG_HI21:
751 // TODO : AArch64 'small' memory model.
752 Error (NULL, 0, 3000, "Invalid", "WriteSections64(): %s unsupported ELF EM_AARCH64 relocation R_AARCH64_ADR_PREL_PG_HI21.", mInImageName);
753 break;
754
755 case R_AARCH64_ADD_ABS_LO12_NC:
756 // TODO : AArch64 'small' memory model.
757 Error (NULL, 0, 3000, "Invalid", "WriteSections64(): %s unsupported ELF EM_AARCH64 relocation R_AARCH64_ADD_ABS_LO12_NC.", mInImageName);
758 break;
759
760 // Absolute relocations.
761 case R_AARCH64_ABS64:
762 *(UINT64 *)Targ = *(UINT64 *)Targ - SymShdr->sh_addr + mCoffSectionsOffset[Sym->st_shndx];
763 break;
764
765 default:
766 Error (NULL, 0, 3000, "Invalid", "WriteSections64(): %s unsupported ELF EM_AARCH64 relocation 0x%x.", mInImageName, (unsigned) ELF_R_TYPE(Rel->r_info));
767 }
768 } else {
769 Error (NULL, 0, 3000, "Invalid", "Not a supported machine type");
770 }
771 }
772 }
773 }
774
775 return TRUE;
776 }
777
778 STATIC
779 VOID
780 WriteRelocations64 (
781 VOID
782 )
783 {
784 UINT32 Index;
785 EFI_IMAGE_OPTIONAL_HEADER_UNION *NtHdr;
786 EFI_IMAGE_DATA_DIRECTORY *Dir;
787
788 for (Index = 0; Index < mEhdr->e_shnum; Index++) {
789 Elf_Shdr *RelShdr = GetShdrByIndex(Index);
790 if ((RelShdr->sh_type == SHT_REL) || (RelShdr->sh_type == SHT_RELA)) {
791 Elf_Shdr *SecShdr = GetShdrByIndex (RelShdr->sh_info);
792 if (IsTextShdr(SecShdr) || IsDataShdr(SecShdr)) {
793 UINT64 RelIdx;
794
795 for (RelIdx = 0; RelIdx < RelShdr->sh_size; RelIdx += RelShdr->sh_entsize) {
796 Elf_Rela *Rel = (Elf_Rela *)((UINT8*)mEhdr + RelShdr->sh_offset + RelIdx);
797
798 if (mEhdr->e_machine == EM_X86_64) {
799 switch (ELF_R_TYPE(Rel->r_info)) {
800 case R_X86_64_NONE:
801 case R_X86_64_PC32:
802 break;
803 case R_X86_64_64:
804 VerboseMsg ("EFI_IMAGE_REL_BASED_DIR64 Offset: 0x%08X",
805 mCoffSectionsOffset[RelShdr->sh_info] + (Rel->r_offset - SecShdr->sh_addr));
806 CoffAddFixup(
807 (UINT32) ((UINT64) mCoffSectionsOffset[RelShdr->sh_info]
808 + (Rel->r_offset - SecShdr->sh_addr)),
809 EFI_IMAGE_REL_BASED_DIR64);
810 break;
811 case R_X86_64_32S:
812 case R_X86_64_32:
813 VerboseMsg ("EFI_IMAGE_REL_BASED_HIGHLOW Offset: 0x%08X",
814 mCoffSectionsOffset[RelShdr->sh_info] + (Rel->r_offset - SecShdr->sh_addr));
815 CoffAddFixup(
816 (UINT32) ((UINT64) mCoffSectionsOffset[RelShdr->sh_info]
817 + (Rel->r_offset - SecShdr->sh_addr)),
818 EFI_IMAGE_REL_BASED_HIGHLOW);
819 break;
820 default:
821 Error (NULL, 0, 3000, "Invalid", "%s unsupported ELF EM_X86_64 relocation 0x%x.", mInImageName, (unsigned) ELF_R_TYPE(Rel->r_info));
822 }
823 } else if (mEhdr->e_machine == EM_AARCH64) {
824 // AArch64 GCC uses RELA relocation, so all relocations has to be fixed up. ARM32 uses REL.
825 switch (ELF_R_TYPE(Rel->r_info)) {
826 case R_AARCH64_ADR_PREL_LO21:
827 break;
828
829 case R_AARCH64_CONDBR19:
830 break;
831
832 case R_AARCH64_LD_PREL_LO19:
833 break;
834
835 case R_AARCH64_CALL26:
836 break;
837
838 case R_AARCH64_JUMP26:
839 break;
840
841 case R_AARCH64_ADR_PREL_PG_HI21:
842 // TODO : AArch64 'small' memory model.
843 Error (NULL, 0, 3000, "Invalid", "WriteRelocations64(): %s unsupported ELF EM_AARCH64 relocation R_AARCH64_ADR_PREL_PG_HI21.", mInImageName);
844 break;
845
846 case R_AARCH64_ADD_ABS_LO12_NC:
847 // TODO : AArch64 'small' memory model.
848 Error (NULL, 0, 3000, "Invalid", "WriteRelocations64(): %s unsupported ELF EM_AARCH64 relocation R_AARCH64_ADD_ABS_LO12_NC.", mInImageName);
849 break;
850
851 case R_AARCH64_ABS64:
852 CoffAddFixup(
853 (UINT32) ((UINT64) mCoffSectionsOffset[RelShdr->sh_info]
854 + (Rel->r_offset - SecShdr->sh_addr)),
855 EFI_IMAGE_REL_BASED_DIR64);
856 break;
857
858 case R_AARCH64_ABS32:
859 CoffAddFixup(
860 (UINT32) ((UINT64) mCoffSectionsOffset[RelShdr->sh_info]
861 + (Rel->r_offset - SecShdr->sh_addr)),
862 EFI_IMAGE_REL_BASED_HIGHLOW);
863 break;
864
865 default:
866 Error (NULL, 0, 3000, "Invalid", "WriteRelocations64(): %s unsupported ELF EM_AARCH64 relocation 0x%x.", mInImageName, (unsigned) ELF_R_TYPE(Rel->r_info));
867 }
868 } else {
869 Error (NULL, 0, 3000, "Not Supported", "This tool does not support relocations for ELF with e_machine %u (processor type).", (unsigned) mEhdr->e_machine);
870 }
871 }
872 }
873 }
874 }
875
876 //
877 // Pad by adding empty entries.
878 //
879 while (mCoffOffset & (mCoffAlignment - 1)) {
880 CoffAddFixupEntry(0);
881 }
882
883 NtHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)(mCoffFile + mNtHdrOffset);
884 Dir = &NtHdr->Pe32Plus.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC];
885 Dir->Size = mCoffOffset - mRelocOffset;
886 if (Dir->Size == 0) {
887 // If no relocations, null out the directory entry and don't add the .reloc section
888 Dir->VirtualAddress = 0;
889 NtHdr->Pe32Plus.FileHeader.NumberOfSections--;
890 } else {
891 Dir->VirtualAddress = mRelocOffset;
892 CreateSectionHeader (".reloc", mRelocOffset, mCoffOffset - mRelocOffset,
893 EFI_IMAGE_SCN_CNT_INITIALIZED_DATA
894 | EFI_IMAGE_SCN_MEM_DISCARDABLE
895 | EFI_IMAGE_SCN_MEM_READ);
896 }
897 }
898
899 STATIC
900 VOID
901 WriteDebug64 (
902 VOID
903 )
904 {
905 UINT32 Len;
906 UINT32 DebugOffset;
907 EFI_IMAGE_OPTIONAL_HEADER_UNION *NtHdr;
908 EFI_IMAGE_DATA_DIRECTORY *DataDir;
909 EFI_IMAGE_DEBUG_DIRECTORY_ENTRY *Dir;
910 EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY *Nb10;
911
912 Len = strlen(mInImageName) + 1;
913 DebugOffset = mCoffOffset;
914
915 mCoffOffset += sizeof(EFI_IMAGE_DEBUG_DIRECTORY_ENTRY)
916 + sizeof(EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY)
917 + Len;
918 mCoffOffset = CoffAlign(mCoffOffset);
919
920 mCoffFile = realloc(mCoffFile, mCoffOffset);
921 memset(mCoffFile + DebugOffset, 0, mCoffOffset - DebugOffset);
922
923 Dir = (EFI_IMAGE_DEBUG_DIRECTORY_ENTRY*)(mCoffFile + DebugOffset);
924 Dir->Type = EFI_IMAGE_DEBUG_TYPE_CODEVIEW;
925 Dir->SizeOfData = sizeof(EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY) + Len;
926 Dir->RVA = DebugOffset + sizeof(EFI_IMAGE_DEBUG_DIRECTORY_ENTRY);
927 Dir->FileOffset = DebugOffset + sizeof(EFI_IMAGE_DEBUG_DIRECTORY_ENTRY);
928
929 Nb10 = (EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY*)(Dir + 1);
930 Nb10->Signature = CODEVIEW_SIGNATURE_NB10;
931 strcpy ((char *)(Nb10 + 1), mInImageName);
932
933
934 NtHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)(mCoffFile + mNtHdrOffset);
935 DataDir = &NtHdr->Pe32Plus.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG];
936 DataDir->VirtualAddress = DebugOffset;
937 DataDir->Size = mCoffOffset - DebugOffset;
938 if (DataDir->Size == 0) {
939 // If no debug, null out the directory entry and don't add the .debug section
940 DataDir->VirtualAddress = 0;
941 NtHdr->Pe32Plus.FileHeader.NumberOfSections--;
942 } else {
943 DataDir->VirtualAddress = DebugOffset;
944 CreateSectionHeader (".debug", DebugOffset, mCoffOffset - DebugOffset,
945 EFI_IMAGE_SCN_CNT_INITIALIZED_DATA
946 | EFI_IMAGE_SCN_MEM_DISCARDABLE
947 | EFI_IMAGE_SCN_MEM_READ);
948
949 }
950 }
951
952 STATIC
953 VOID
954 SetImageSize64 (
955 VOID
956 )
957 {
958 EFI_IMAGE_OPTIONAL_HEADER_UNION *NtHdr;
959
960 //
961 // Set image size
962 //
963 NtHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)(mCoffFile + mNtHdrOffset);
964 NtHdr->Pe32Plus.OptionalHeader.SizeOfImage = mCoffOffset;
965 }
966
967 STATIC
968 VOID
969 CleanUp64 (
970 VOID
971 )
972 {
973 if (mCoffSectionsOffset != NULL) {
974 free (mCoffSectionsOffset);
975 }
976 }
977
978