]> git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Source/C/GenFw/Elf64Convert.c
BaseTools/GenFw: Enhance error message for bad symbol definitions
[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 = 4;
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 STATIC UINT32 mDebugOffset;
121
122 //
123 // Initialization Function
124 //
125 BOOLEAN
126 InitializeElf64 (
127 UINT8 *FileBuffer,
128 ELF_FUNCTION_TABLE *ElfFunctions
129 )
130 {
131 //
132 // Initialize data pointer and structures.
133 //
134 VerboseMsg ("Set EHDR");
135 mEhdr = (Elf_Ehdr*) FileBuffer;
136
137 //
138 // Check the ELF64 specific header information.
139 //
140 VerboseMsg ("Check ELF64 Header Information");
141 if (mEhdr->e_ident[EI_CLASS] != ELFCLASS64) {
142 Error (NULL, 0, 3000, "Unsupported", "ELF EI_DATA not ELFCLASS64");
143 return FALSE;
144 }
145 if (mEhdr->e_ident[EI_DATA] != ELFDATA2LSB) {
146 Error (NULL, 0, 3000, "Unsupported", "ELF EI_DATA not ELFDATA2LSB");
147 return FALSE;
148 }
149 if ((mEhdr->e_type != ET_EXEC) && (mEhdr->e_type != ET_DYN)) {
150 Error (NULL, 0, 3000, "Unsupported", "ELF e_type not ET_EXEC or ET_DYN");
151 return FALSE;
152 }
153 if (!((mEhdr->e_machine == EM_X86_64) || (mEhdr->e_machine == EM_AARCH64))) {
154 Error (NULL, 0, 3000, "Unsupported", "ELF e_machine not EM_X86_64 or EM_AARCH64");
155 return FALSE;
156 }
157 if (mEhdr->e_version != EV_CURRENT) {
158 Error (NULL, 0, 3000, "Unsupported", "ELF e_version (%u) not EV_CURRENT (%d)", (unsigned) mEhdr->e_version, EV_CURRENT);
159 return FALSE;
160 }
161
162 //
163 // Update section header pointers
164 //
165 VerboseMsg ("Update Header Pointers");
166 mShdrBase = (Elf_Shdr *)((UINT8 *)mEhdr + mEhdr->e_shoff);
167 mPhdrBase = (Elf_Phdr *)((UINT8 *)mEhdr + mEhdr->e_phoff);
168
169 //
170 // Create COFF Section offset buffer and zero.
171 //
172 VerboseMsg ("Create COFF Section Offset Buffer");
173 mCoffSectionsOffset = (UINT32 *)malloc(mEhdr->e_shnum * sizeof (UINT32));
174 memset(mCoffSectionsOffset, 0, mEhdr->e_shnum * sizeof(UINT32));
175
176 //
177 // Fill in function pointers.
178 //
179 VerboseMsg ("Fill in Function Pointers");
180 ElfFunctions->ScanSections = ScanSections64;
181 ElfFunctions->WriteSections = WriteSections64;
182 ElfFunctions->WriteRelocations = WriteRelocations64;
183 ElfFunctions->WriteDebug = WriteDebug64;
184 ElfFunctions->SetImageSize = SetImageSize64;
185 ElfFunctions->CleanUp = CleanUp64;
186
187 return TRUE;
188 }
189
190
191 //
192 // Header by Index functions
193 //
194 STATIC
195 Elf_Shdr*
196 GetShdrByIndex (
197 UINT32 Num
198 )
199 {
200 if (Num >= mEhdr->e_shnum) {
201 Error (NULL, 0, 3000, "Invalid", "GetShdrByIndex: Index %u is too high.", Num);
202 exit(EXIT_FAILURE);
203 }
204
205 return (Elf_Shdr*)((UINT8*)mShdrBase + Num * mEhdr->e_shentsize);
206 }
207
208 STATIC
209 UINT32
210 CoffAlign (
211 UINT32 Offset
212 )
213 {
214 return (Offset + mCoffAlignment - 1) & ~(mCoffAlignment - 1);
215 }
216
217 STATIC
218 UINT32
219 DebugRvaAlign (
220 UINT32 Offset
221 )
222 {
223 return (Offset + 3) & ~3;
224 }
225
226 //
227 // filter functions
228 //
229 STATIC
230 BOOLEAN
231 IsTextShdr (
232 Elf_Shdr *Shdr
233 )
234 {
235 return (BOOLEAN) ((Shdr->sh_flags & (SHF_WRITE | SHF_ALLOC)) == SHF_ALLOC);
236 }
237
238 STATIC
239 BOOLEAN
240 IsHiiRsrcShdr (
241 Elf_Shdr *Shdr
242 )
243 {
244 Elf_Shdr *Namedr = GetShdrByIndex(mEhdr->e_shstrndx);
245
246 return (BOOLEAN) (strcmp((CHAR8*)mEhdr + Namedr->sh_offset + Shdr->sh_name, ELF_HII_SECTION_NAME) == 0);
247 }
248
249 STATIC
250 BOOLEAN
251 IsDataShdr (
252 Elf_Shdr *Shdr
253 )
254 {
255 if (IsHiiRsrcShdr(Shdr)) {
256 return FALSE;
257 }
258 return (BOOLEAN) (Shdr->sh_flags & (SHF_WRITE | SHF_ALLOC)) == (SHF_ALLOC | SHF_WRITE);
259 }
260
261 STATIC
262 BOOLEAN
263 IsStrtabShdr (
264 Elf_Shdr *Shdr
265 )
266 {
267 Elf_Shdr *Namedr = GetShdrByIndex(mEhdr->e_shstrndx);
268
269 return (BOOLEAN) (strcmp((CHAR8*)mEhdr + Namedr->sh_offset + Shdr->sh_name, ELF_STRTAB_SECTION_NAME) == 0);
270 }
271
272 STATIC
273 Elf_Shdr *
274 FindStrtabShdr (
275 VOID
276 )
277 {
278 UINT32 i;
279 for (i = 0; i < mEhdr->e_shnum; i++) {
280 Elf_Shdr *shdr = GetShdrByIndex(i);
281 if (IsStrtabShdr(shdr)) {
282 return shdr;
283 }
284 }
285 return NULL;
286 }
287
288 STATIC
289 const UINT8 *
290 GetSymName (
291 Elf_Sym *Sym
292 )
293 {
294 if (Sym->st_name == 0) {
295 return NULL;
296 }
297
298 Elf_Shdr *StrtabShdr = FindStrtabShdr();
299 if (StrtabShdr == NULL) {
300 return NULL;
301 }
302
303 assert(Sym->st_name < StrtabShdr->sh_size);
304
305 return (UINT8*)mEhdr + StrtabShdr->sh_offset + Sym->st_name;
306 }
307
308 //
309 // Elf functions interface implementation
310 //
311
312 STATIC
313 VOID
314 ScanSections64 (
315 VOID
316 )
317 {
318 UINT32 i;
319 EFI_IMAGE_DOS_HEADER *DosHdr;
320 EFI_IMAGE_OPTIONAL_HEADER_UNION *NtHdr;
321 UINT32 CoffEntry;
322 UINT32 SectionCount;
323 BOOLEAN FoundSection;
324
325 CoffEntry = 0;
326 mCoffOffset = 0;
327
328 //
329 // Coff file start with a DOS header.
330 //
331 mCoffOffset = sizeof(EFI_IMAGE_DOS_HEADER) + 0x40;
332 mNtHdrOffset = mCoffOffset;
333 switch (mEhdr->e_machine) {
334 case EM_X86_64:
335 case EM_IA_64:
336 case EM_AARCH64:
337 mCoffOffset += sizeof (EFI_IMAGE_NT_HEADERS64);
338 break;
339 default:
340 VerboseMsg ("%s unknown e_machine type. Assume X64", (UINTN)mEhdr->e_machine);
341 mCoffOffset += sizeof (EFI_IMAGE_NT_HEADERS64);
342 break;
343 }
344
345 mTableOffset = mCoffOffset;
346 mCoffOffset += mCoffNbrSections * sizeof(EFI_IMAGE_SECTION_HEADER);
347
348 //
349 // Set mCoffAlignment to the maximum alignment of the input sections
350 // we care about
351 //
352 for (i = 0; i < mEhdr->e_shnum; i++) {
353 Elf_Shdr *shdr = GetShdrByIndex(i);
354 if (shdr->sh_addralign <= mCoffAlignment) {
355 continue;
356 }
357 if (IsTextShdr(shdr) || IsDataShdr(shdr) || IsHiiRsrcShdr(shdr)) {
358 mCoffAlignment = (UINT32)shdr->sh_addralign;
359 }
360 }
361
362 //
363 // Move the PE/COFF header right before the first section. This will help us
364 // save space when converting to TE.
365 //
366 if (mCoffAlignment > mCoffOffset) {
367 mNtHdrOffset += mCoffAlignment - mCoffOffset;
368 mTableOffset += mCoffAlignment - mCoffOffset;
369 mCoffOffset = mCoffAlignment;
370 }
371
372 //
373 // First text sections.
374 //
375 mCoffOffset = CoffAlign(mCoffOffset);
376 mTextOffset = mCoffOffset;
377 FoundSection = FALSE;
378 SectionCount = 0;
379 for (i = 0; i < mEhdr->e_shnum; i++) {
380 Elf_Shdr *shdr = GetShdrByIndex(i);
381 if (IsTextShdr(shdr)) {
382 if ((shdr->sh_addralign != 0) && (shdr->sh_addralign != 1)) {
383 // the alignment field is valid
384 if ((shdr->sh_addr & (shdr->sh_addralign - 1)) == 0) {
385 // if the section address is aligned we must align PE/COFF
386 mCoffOffset = (UINT32) ((mCoffOffset + shdr->sh_addralign - 1) & ~(shdr->sh_addralign - 1));
387 } else {
388 Error (NULL, 0, 3000, "Invalid", "Section address not aligned to its own alignment.");
389 }
390 }
391
392 /* Relocate entry. */
393 if ((mEhdr->e_entry >= shdr->sh_addr) &&
394 (mEhdr->e_entry < shdr->sh_addr + shdr->sh_size)) {
395 CoffEntry = (UINT32) (mCoffOffset + mEhdr->e_entry - shdr->sh_addr);
396 }
397
398 //
399 // Set mTextOffset with the offset of the first '.text' section
400 //
401 if (!FoundSection) {
402 mTextOffset = mCoffOffset;
403 FoundSection = TRUE;
404 }
405
406 mCoffSectionsOffset[i] = mCoffOffset;
407 mCoffOffset += (UINT32) shdr->sh_size;
408 SectionCount ++;
409 }
410 }
411
412 if (!FoundSection) {
413 Error (NULL, 0, 3000, "Invalid", "Did not find any '.text' section.");
414 assert (FALSE);
415 }
416
417 mDebugOffset = DebugRvaAlign(mCoffOffset);
418 mCoffOffset = CoffAlign(mCoffOffset);
419
420 if (SectionCount > 1 && mOutImageType == FW_EFI_IMAGE) {
421 Warning (NULL, 0, 0, NULL, "Mulitple sections in %s are merged into 1 text section. Source level debug might not work correctly.", mInImageName);
422 }
423
424 //
425 // Then data sections.
426 //
427 mDataOffset = mCoffOffset;
428 FoundSection = FALSE;
429 SectionCount = 0;
430 for (i = 0; i < mEhdr->e_shnum; i++) {
431 Elf_Shdr *shdr = GetShdrByIndex(i);
432 if (IsDataShdr(shdr)) {
433 if ((shdr->sh_addralign != 0) && (shdr->sh_addralign != 1)) {
434 // the alignment field is valid
435 if ((shdr->sh_addr & (shdr->sh_addralign - 1)) == 0) {
436 // if the section address is aligned we must align PE/COFF
437 mCoffOffset = (UINT32) ((mCoffOffset + shdr->sh_addralign - 1) & ~(shdr->sh_addralign - 1));
438 } else {
439 Error (NULL, 0, 3000, "Invalid", "Section address not aligned to its own alignment.");
440 }
441 }
442
443 //
444 // Set mDataOffset with the offset of the first '.data' section
445 //
446 if (!FoundSection) {
447 mDataOffset = mCoffOffset;
448 FoundSection = TRUE;
449 }
450 mCoffSectionsOffset[i] = mCoffOffset;
451 mCoffOffset += (UINT32) shdr->sh_size;
452 SectionCount ++;
453 }
454 }
455
456 //
457 // Make room for .debug data in .data (or .text if .data is empty) instead of
458 // putting it in a section of its own. This is explicitly allowed by the
459 // PE/COFF spec, and prevents bloat in the binary when using large values for
460 // section alignment.
461 //
462 if (SectionCount > 0) {
463 mDebugOffset = DebugRvaAlign(mCoffOffset);
464 }
465 mCoffOffset = mDebugOffset + sizeof(EFI_IMAGE_DEBUG_DIRECTORY_ENTRY) +
466 sizeof(EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY) +
467 strlen(mInImageName) + 1;
468
469 mCoffOffset = CoffAlign(mCoffOffset);
470 if (SectionCount == 0) {
471 mDataOffset = mCoffOffset;
472 }
473
474 if (SectionCount > 1 && mOutImageType == FW_EFI_IMAGE) {
475 Warning (NULL, 0, 0, NULL, "Mulitple sections in %s are merged into 1 data section. Source level debug might not work correctly.", mInImageName);
476 }
477
478 //
479 // The HII resource sections.
480 //
481 mHiiRsrcOffset = mCoffOffset;
482 for (i = 0; i < mEhdr->e_shnum; i++) {
483 Elf_Shdr *shdr = GetShdrByIndex(i);
484 if (IsHiiRsrcShdr(shdr)) {
485 if ((shdr->sh_addralign != 0) && (shdr->sh_addralign != 1)) {
486 // the alignment field is valid
487 if ((shdr->sh_addr & (shdr->sh_addralign - 1)) == 0) {
488 // if the section address is aligned we must align PE/COFF
489 mCoffOffset = (UINT32) ((mCoffOffset + shdr->sh_addralign - 1) & ~(shdr->sh_addralign - 1));
490 } else {
491 Error (NULL, 0, 3000, "Invalid", "Section address not aligned to its own alignment.");
492 }
493 }
494 if (shdr->sh_size != 0) {
495 mHiiRsrcOffset = mCoffOffset;
496 mCoffSectionsOffset[i] = mCoffOffset;
497 mCoffOffset += (UINT32) shdr->sh_size;
498 mCoffOffset = CoffAlign(mCoffOffset);
499 SetHiiResourceHeader ((UINT8*) mEhdr + shdr->sh_offset, mHiiRsrcOffset);
500 }
501 break;
502 }
503 }
504
505 mRelocOffset = mCoffOffset;
506
507 //
508 // Allocate base Coff file. Will be expanded later for relocations.
509 //
510 mCoffFile = (UINT8 *)malloc(mCoffOffset);
511 memset(mCoffFile, 0, mCoffOffset);
512
513 //
514 // Fill headers.
515 //
516 DosHdr = (EFI_IMAGE_DOS_HEADER *)mCoffFile;
517 DosHdr->e_magic = EFI_IMAGE_DOS_SIGNATURE;
518 DosHdr->e_lfanew = mNtHdrOffset;
519
520 NtHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION*)(mCoffFile + mNtHdrOffset);
521
522 NtHdr->Pe32Plus.Signature = EFI_IMAGE_NT_SIGNATURE;
523
524 switch (mEhdr->e_machine) {
525 case EM_X86_64:
526 NtHdr->Pe32Plus.FileHeader.Machine = EFI_IMAGE_MACHINE_X64;
527 NtHdr->Pe32Plus.OptionalHeader.Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC;
528 break;
529 case EM_IA_64:
530 NtHdr->Pe32Plus.FileHeader.Machine = EFI_IMAGE_MACHINE_IPF;
531 NtHdr->Pe32Plus.OptionalHeader.Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC;
532 break;
533 case EM_AARCH64:
534 NtHdr->Pe32Plus.FileHeader.Machine = EFI_IMAGE_MACHINE_AARCH64;
535 NtHdr->Pe32Plus.OptionalHeader.Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC;
536 break;
537 default:
538 VerboseMsg ("%s unknown e_machine type. Assume X64", (UINTN)mEhdr->e_machine);
539 NtHdr->Pe32Plus.FileHeader.Machine = EFI_IMAGE_MACHINE_X64;
540 NtHdr->Pe32Plus.OptionalHeader.Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC;
541 }
542
543 NtHdr->Pe32Plus.FileHeader.NumberOfSections = mCoffNbrSections;
544 NtHdr->Pe32Plus.FileHeader.TimeDateStamp = (UINT32) time(NULL);
545 mImageTimeStamp = NtHdr->Pe32Plus.FileHeader.TimeDateStamp;
546 NtHdr->Pe32Plus.FileHeader.PointerToSymbolTable = 0;
547 NtHdr->Pe32Plus.FileHeader.NumberOfSymbols = 0;
548 NtHdr->Pe32Plus.FileHeader.SizeOfOptionalHeader = sizeof(NtHdr->Pe32Plus.OptionalHeader);
549 NtHdr->Pe32Plus.FileHeader.Characteristics = EFI_IMAGE_FILE_EXECUTABLE_IMAGE
550 | EFI_IMAGE_FILE_LINE_NUMS_STRIPPED
551 | EFI_IMAGE_FILE_LOCAL_SYMS_STRIPPED
552 | EFI_IMAGE_FILE_LARGE_ADDRESS_AWARE;
553
554 NtHdr->Pe32Plus.OptionalHeader.SizeOfCode = mDataOffset - mTextOffset;
555 NtHdr->Pe32Plus.OptionalHeader.SizeOfInitializedData = mRelocOffset - mDataOffset;
556 NtHdr->Pe32Plus.OptionalHeader.SizeOfUninitializedData = 0;
557 NtHdr->Pe32Plus.OptionalHeader.AddressOfEntryPoint = CoffEntry;
558
559 NtHdr->Pe32Plus.OptionalHeader.BaseOfCode = mTextOffset;
560
561 NtHdr->Pe32Plus.OptionalHeader.ImageBase = 0;
562 NtHdr->Pe32Plus.OptionalHeader.SectionAlignment = mCoffAlignment;
563 NtHdr->Pe32Plus.OptionalHeader.FileAlignment = mCoffAlignment;
564 NtHdr->Pe32Plus.OptionalHeader.SizeOfImage = 0;
565
566 NtHdr->Pe32Plus.OptionalHeader.SizeOfHeaders = mTextOffset;
567 NtHdr->Pe32Plus.OptionalHeader.NumberOfRvaAndSizes = EFI_IMAGE_NUMBER_OF_DIRECTORY_ENTRIES;
568
569 //
570 // Section headers.
571 //
572 if ((mDataOffset - mTextOffset) > 0) {
573 CreateSectionHeader (".text", mTextOffset, mDataOffset - mTextOffset,
574 EFI_IMAGE_SCN_CNT_CODE
575 | EFI_IMAGE_SCN_MEM_EXECUTE
576 | EFI_IMAGE_SCN_MEM_READ);
577 } else {
578 // Don't make a section of size 0.
579 NtHdr->Pe32Plus.FileHeader.NumberOfSections--;
580 }
581
582 if ((mHiiRsrcOffset - mDataOffset) > 0) {
583 CreateSectionHeader (".data", mDataOffset, mHiiRsrcOffset - mDataOffset,
584 EFI_IMAGE_SCN_CNT_INITIALIZED_DATA
585 | EFI_IMAGE_SCN_MEM_WRITE
586 | EFI_IMAGE_SCN_MEM_READ);
587 } else {
588 // Don't make a section of size 0.
589 NtHdr->Pe32Plus.FileHeader.NumberOfSections--;
590 }
591
592 if ((mRelocOffset - mHiiRsrcOffset) > 0) {
593 CreateSectionHeader (".rsrc", mHiiRsrcOffset, mRelocOffset - mHiiRsrcOffset,
594 EFI_IMAGE_SCN_CNT_INITIALIZED_DATA
595 | EFI_IMAGE_SCN_MEM_READ);
596
597 NtHdr->Pe32Plus.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE].Size = mRelocOffset - mHiiRsrcOffset;
598 NtHdr->Pe32Plus.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress = mHiiRsrcOffset;
599 } else {
600 // Don't make a section of size 0.
601 NtHdr->Pe32Plus.FileHeader.NumberOfSections--;
602 }
603
604 }
605
606 STATIC
607 BOOLEAN
608 WriteSections64 (
609 SECTION_FILTER_TYPES FilterType
610 )
611 {
612 UINT32 Idx;
613 Elf_Shdr *SecShdr;
614 UINT32 SecOffset;
615 BOOLEAN (*Filter)(Elf_Shdr *);
616
617 //
618 // Initialize filter pointer
619 //
620 switch (FilterType) {
621 case SECTION_TEXT:
622 Filter = IsTextShdr;
623 break;
624 case SECTION_HII:
625 Filter = IsHiiRsrcShdr;
626 break;
627 case SECTION_DATA:
628 Filter = IsDataShdr;
629 break;
630 default:
631 return FALSE;
632 }
633
634 //
635 // First: copy sections.
636 //
637 for (Idx = 0; Idx < mEhdr->e_shnum; Idx++) {
638 Elf_Shdr *Shdr = GetShdrByIndex(Idx);
639 if ((*Filter)(Shdr)) {
640 switch (Shdr->sh_type) {
641 case SHT_PROGBITS:
642 /* Copy. */
643 memcpy(mCoffFile + mCoffSectionsOffset[Idx],
644 (UINT8*)mEhdr + Shdr->sh_offset,
645 (size_t) Shdr->sh_size);
646 break;
647
648 case SHT_NOBITS:
649 memset(mCoffFile + mCoffSectionsOffset[Idx], 0, (size_t) Shdr->sh_size);
650 break;
651
652 default:
653 //
654 // Ignore for unkown section type.
655 //
656 VerboseMsg ("%s unknown section type %x. We directly copy this section into Coff file", mInImageName, (unsigned)Shdr->sh_type);
657 break;
658 }
659 }
660 }
661
662 //
663 // Second: apply relocations.
664 //
665 VerboseMsg ("Applying Relocations...");
666 for (Idx = 0; Idx < mEhdr->e_shnum; Idx++) {
667 //
668 // Determine if this is a relocation section.
669 //
670 Elf_Shdr *RelShdr = GetShdrByIndex(Idx);
671 if ((RelShdr->sh_type != SHT_REL) && (RelShdr->sh_type != SHT_RELA)) {
672 continue;
673 }
674
675 //
676 // Relocation section found. Now extract section information that the relocations
677 // apply to in the ELF data and the new COFF data.
678 //
679 SecShdr = GetShdrByIndex(RelShdr->sh_info);
680 SecOffset = mCoffSectionsOffset[RelShdr->sh_info];
681
682 //
683 // Only process relocations for the current filter type.
684 //
685 if (RelShdr->sh_type == SHT_RELA && (*Filter)(SecShdr)) {
686 UINT64 RelIdx;
687
688 //
689 // Determine the symbol table referenced by the relocation data.
690 //
691 Elf_Shdr *SymtabShdr = GetShdrByIndex(RelShdr->sh_link);
692 UINT8 *Symtab = (UINT8*)mEhdr + SymtabShdr->sh_offset;
693
694 //
695 // Process all relocation entries for this section.
696 //
697 for (RelIdx = 0; RelIdx < RelShdr->sh_size; RelIdx += (UINT32) RelShdr->sh_entsize) {
698
699 //
700 // Set pointer to relocation entry
701 //
702 Elf_Rela *Rel = (Elf_Rela *)((UINT8*)mEhdr + RelShdr->sh_offset + RelIdx);
703
704 //
705 // Set pointer to symbol table entry associated with the relocation entry.
706 //
707 Elf_Sym *Sym = (Elf_Sym *)(Symtab + ELF_R_SYM(Rel->r_info) * SymtabShdr->sh_entsize);
708
709 Elf_Shdr *SymShdr;
710 UINT8 *Targ;
711
712 //
713 // Check section header index found in symbol table and get the section
714 // header location.
715 //
716 if (Sym->st_shndx == SHN_UNDEF
717 || Sym->st_shndx >= mEhdr->e_shnum) {
718 const UINT8 *SymName = GetSymName(Sym);
719 if (SymName == NULL) {
720 SymName = (const UINT8 *)"<unknown>";
721 }
722
723 Error (NULL, 0, 3000, "Invalid",
724 "%s: Bad definition for symbol '%s'@%p or unsupported symbol type. "
725 "For example, absolute and undefined symbols are not supported.",
726 mInImageName, SymName, Sym->st_value);
727
728 exit(EXIT_FAILURE);
729 }
730 SymShdr = GetShdrByIndex(Sym->st_shndx);
731
732 //
733 // Convert the relocation data to a pointer into the coff file.
734 //
735 // Note:
736 // r_offset is the virtual address of the storage unit to be relocated.
737 // sh_addr is the virtual address for the base of the section.
738 //
739 // r_offset in a memory address.
740 // Convert it to a pointer in the coff file.
741 //
742 Targ = mCoffFile + SecOffset + (Rel->r_offset - SecShdr->sh_addr);
743
744 //
745 // Determine how to handle each relocation type based on the machine type.
746 //
747 if (mEhdr->e_machine == EM_X86_64) {
748 switch (ELF_R_TYPE(Rel->r_info)) {
749 case R_X86_64_NONE:
750 break;
751 case R_X86_64_64:
752 //
753 // Absolute relocation.
754 //
755 VerboseMsg ("R_X86_64_64");
756 VerboseMsg ("Offset: 0x%08X, Addend: 0x%016LX",
757 (UINT32)(SecOffset + (Rel->r_offset - SecShdr->sh_addr)),
758 *(UINT64 *)Targ);
759 *(UINT64 *)Targ = *(UINT64 *)Targ - SymShdr->sh_addr + mCoffSectionsOffset[Sym->st_shndx];
760 VerboseMsg ("Relocation: 0x%016LX", *(UINT64*)Targ);
761 break;
762 case R_X86_64_32:
763 VerboseMsg ("R_X86_64_32");
764 VerboseMsg ("Offset: 0x%08X, Addend: 0x%08X",
765 (UINT32)(SecOffset + (Rel->r_offset - SecShdr->sh_addr)),
766 *(UINT32 *)Targ);
767 *(UINT32 *)Targ = (UINT32)((UINT64)(*(UINT32 *)Targ) - SymShdr->sh_addr + mCoffSectionsOffset[Sym->st_shndx]);
768 VerboseMsg ("Relocation: 0x%08X", *(UINT32*)Targ);
769 break;
770 case R_X86_64_32S:
771 VerboseMsg ("R_X86_64_32S");
772 VerboseMsg ("Offset: 0x%08X, Addend: 0x%08X",
773 (UINT32)(SecOffset + (Rel->r_offset - SecShdr->sh_addr)),
774 *(UINT32 *)Targ);
775 *(INT32 *)Targ = (INT32)((INT64)(*(INT32 *)Targ) - SymShdr->sh_addr + mCoffSectionsOffset[Sym->st_shndx]);
776 VerboseMsg ("Relocation: 0x%08X", *(UINT32*)Targ);
777 break;
778 case R_X86_64_PC32:
779 //
780 // Relative relocation: Symbol - Ip + Addend
781 //
782 VerboseMsg ("R_X86_64_PC32");
783 VerboseMsg ("Offset: 0x%08X, Addend: 0x%08X",
784 (UINT32)(SecOffset + (Rel->r_offset - SecShdr->sh_addr)),
785 *(UINT32 *)Targ);
786 *(UINT32 *)Targ = (UINT32) (*(UINT32 *)Targ
787 + (mCoffSectionsOffset[Sym->st_shndx] - SymShdr->sh_addr)
788 - (SecOffset - SecShdr->sh_addr));
789 VerboseMsg ("Relocation: 0x%08X", *(UINT32 *)Targ);
790 break;
791 default:
792 Error (NULL, 0, 3000, "Invalid", "%s unsupported ELF EM_X86_64 relocation 0x%x.", mInImageName, (unsigned) ELF_R_TYPE(Rel->r_info));
793 }
794 } else if (mEhdr->e_machine == EM_AARCH64) {
795
796 switch (ELF_R_TYPE(Rel->r_info)) {
797
798 case R_AARCH64_ADR_PREL_PG_HI21:
799 case R_AARCH64_ADD_ABS_LO12_NC:
800 case R_AARCH64_LDST8_ABS_LO12_NC:
801 case R_AARCH64_LDST16_ABS_LO12_NC:
802 case R_AARCH64_LDST32_ABS_LO12_NC:
803 case R_AARCH64_LDST64_ABS_LO12_NC:
804 case R_AARCH64_LDST128_ABS_LO12_NC:
805 //
806 // AArch64 PG_H21 relocations are typically paired with ABS_LO12
807 // relocations, where a PC-relative reference with +/- 4 GB range is
808 // split into a relative high part and an absolute low part. Since
809 // the absolute low part represents the offset into a 4 KB page, we
810 // have to make sure that the 4 KB relative offsets of both the
811 // section containing the reference as well as the section to which
812 // it refers have not been changed during PE/COFF conversion (i.e.,
813 // in ScanSections64() above).
814 //
815 if (((SecShdr->sh_addr ^ SecOffset) & 0xfff) != 0 ||
816 ((SymShdr->sh_addr ^ mCoffSectionsOffset[Sym->st_shndx]) & 0xfff) != 0 ||
817 mCoffAlignment < 0x1000) {
818 Error (NULL, 0, 3000, "Invalid", "WriteSections64(): %s AARCH64 small code model requires 4 KB section alignment.",
819 mInImageName);
820 break;
821 }
822 /* fall through */
823
824 case R_AARCH64_ADR_PREL_LO21:
825 case R_AARCH64_CONDBR19:
826 case R_AARCH64_LD_PREL_LO19:
827 case R_AARCH64_CALL26:
828 case R_AARCH64_JUMP26:
829 case R_AARCH64_PREL64:
830 case R_AARCH64_PREL32:
831 case R_AARCH64_PREL16:
832 //
833 // The GCC toolchains (i.e., binutils) may corrupt section relative
834 // relocations when emitting relocation sections into fully linked
835 // binaries. More specifically, they tend to fail to take into
836 // account the fact that a '.rodata + XXX' relocation needs to have
837 // its addend recalculated once .rodata is merged into the .text
838 // section, and the relocation emitted into the .rela.text section.
839 //
840 // We cannot really recover from this loss of information, so the
841 // only workaround is to prevent having to recalculate any relative
842 // relocations at all, by using a linker script that ensures that
843 // the offset between the Place and the Symbol is the same in both
844 // the ELF and the PE/COFF versions of the binary.
845 //
846 if ((SymShdr->sh_addr - SecShdr->sh_addr) !=
847 (mCoffSectionsOffset[Sym->st_shndx] - SecOffset)) {
848 Error (NULL, 0, 3000, "Invalid", "WriteSections64(): %s AARCH64 relative relocations require identical ELF and PE/COFF section offsets",
849 mInImageName);
850 }
851 break;
852
853 // Absolute relocations.
854 case R_AARCH64_ABS64:
855 *(UINT64 *)Targ = *(UINT64 *)Targ - SymShdr->sh_addr + mCoffSectionsOffset[Sym->st_shndx];
856 break;
857
858 default:
859 Error (NULL, 0, 3000, "Invalid", "WriteSections64(): %s unsupported ELF EM_AARCH64 relocation 0x%x.", mInImageName, (unsigned) ELF_R_TYPE(Rel->r_info));
860 }
861 } else {
862 Error (NULL, 0, 3000, "Invalid", "Not a supported machine type");
863 }
864 }
865 }
866 }
867
868 return TRUE;
869 }
870
871 STATIC
872 VOID
873 WriteRelocations64 (
874 VOID
875 )
876 {
877 UINT32 Index;
878 EFI_IMAGE_OPTIONAL_HEADER_UNION *NtHdr;
879 EFI_IMAGE_DATA_DIRECTORY *Dir;
880
881 for (Index = 0; Index < mEhdr->e_shnum; Index++) {
882 Elf_Shdr *RelShdr = GetShdrByIndex(Index);
883 if ((RelShdr->sh_type == SHT_REL) || (RelShdr->sh_type == SHT_RELA)) {
884 Elf_Shdr *SecShdr = GetShdrByIndex (RelShdr->sh_info);
885 if (IsTextShdr(SecShdr) || IsDataShdr(SecShdr)) {
886 UINT64 RelIdx;
887
888 for (RelIdx = 0; RelIdx < RelShdr->sh_size; RelIdx += RelShdr->sh_entsize) {
889 Elf_Rela *Rel = (Elf_Rela *)((UINT8*)mEhdr + RelShdr->sh_offset + RelIdx);
890
891 if (mEhdr->e_machine == EM_X86_64) {
892 switch (ELF_R_TYPE(Rel->r_info)) {
893 case R_X86_64_NONE:
894 case R_X86_64_PC32:
895 break;
896 case R_X86_64_64:
897 VerboseMsg ("EFI_IMAGE_REL_BASED_DIR64 Offset: 0x%08X",
898 mCoffSectionsOffset[RelShdr->sh_info] + (Rel->r_offset - SecShdr->sh_addr));
899 CoffAddFixup(
900 (UINT32) ((UINT64) mCoffSectionsOffset[RelShdr->sh_info]
901 + (Rel->r_offset - SecShdr->sh_addr)),
902 EFI_IMAGE_REL_BASED_DIR64);
903 break;
904 case R_X86_64_32S:
905 case R_X86_64_32:
906 VerboseMsg ("EFI_IMAGE_REL_BASED_HIGHLOW Offset: 0x%08X",
907 mCoffSectionsOffset[RelShdr->sh_info] + (Rel->r_offset - SecShdr->sh_addr));
908 CoffAddFixup(
909 (UINT32) ((UINT64) mCoffSectionsOffset[RelShdr->sh_info]
910 + (Rel->r_offset - SecShdr->sh_addr)),
911 EFI_IMAGE_REL_BASED_HIGHLOW);
912 break;
913 default:
914 Error (NULL, 0, 3000, "Invalid", "%s unsupported ELF EM_X86_64 relocation 0x%x.", mInImageName, (unsigned) ELF_R_TYPE(Rel->r_info));
915 }
916 } else if (mEhdr->e_machine == EM_AARCH64) {
917
918 switch (ELF_R_TYPE(Rel->r_info)) {
919 case R_AARCH64_ADR_PREL_LO21:
920 case R_AARCH64_CONDBR19:
921 case R_AARCH64_LD_PREL_LO19:
922 case R_AARCH64_CALL26:
923 case R_AARCH64_JUMP26:
924 case R_AARCH64_PREL64:
925 case R_AARCH64_PREL32:
926 case R_AARCH64_PREL16:
927 case R_AARCH64_ADR_PREL_PG_HI21:
928 case R_AARCH64_ADD_ABS_LO12_NC:
929 case R_AARCH64_LDST8_ABS_LO12_NC:
930 case R_AARCH64_LDST16_ABS_LO12_NC:
931 case R_AARCH64_LDST32_ABS_LO12_NC:
932 case R_AARCH64_LDST64_ABS_LO12_NC:
933 case R_AARCH64_LDST128_ABS_LO12_NC:
934 //
935 // No fixups are required for relative relocations, provided that
936 // the relative offsets between sections have been preserved in
937 // the ELF to PE/COFF conversion. We have already asserted that
938 // this is the case in WriteSections64 ().
939 //
940 break;
941
942 case R_AARCH64_ABS64:
943 CoffAddFixup(
944 (UINT32) ((UINT64) mCoffSectionsOffset[RelShdr->sh_info]
945 + (Rel->r_offset - SecShdr->sh_addr)),
946 EFI_IMAGE_REL_BASED_DIR64);
947 break;
948
949 case R_AARCH64_ABS32:
950 CoffAddFixup(
951 (UINT32) ((UINT64) mCoffSectionsOffset[RelShdr->sh_info]
952 + (Rel->r_offset - SecShdr->sh_addr)),
953 EFI_IMAGE_REL_BASED_HIGHLOW);
954 break;
955
956 default:
957 Error (NULL, 0, 3000, "Invalid", "WriteRelocations64(): %s unsupported ELF EM_AARCH64 relocation 0x%x.", mInImageName, (unsigned) ELF_R_TYPE(Rel->r_info));
958 }
959 } else {
960 Error (NULL, 0, 3000, "Not Supported", "This tool does not support relocations for ELF with e_machine %u (processor type).", (unsigned) mEhdr->e_machine);
961 }
962 }
963 }
964 }
965 }
966
967 //
968 // Pad by adding empty entries.
969 //
970 while (mCoffOffset & (mCoffAlignment - 1)) {
971 CoffAddFixupEntry(0);
972 }
973
974 NtHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)(mCoffFile + mNtHdrOffset);
975 Dir = &NtHdr->Pe32Plus.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC];
976 Dir->Size = mCoffOffset - mRelocOffset;
977 if (Dir->Size == 0) {
978 // If no relocations, null out the directory entry and don't add the .reloc section
979 Dir->VirtualAddress = 0;
980 NtHdr->Pe32Plus.FileHeader.NumberOfSections--;
981 } else {
982 Dir->VirtualAddress = mRelocOffset;
983 CreateSectionHeader (".reloc", mRelocOffset, mCoffOffset - mRelocOffset,
984 EFI_IMAGE_SCN_CNT_INITIALIZED_DATA
985 | EFI_IMAGE_SCN_MEM_DISCARDABLE
986 | EFI_IMAGE_SCN_MEM_READ);
987 }
988 }
989
990 STATIC
991 VOID
992 WriteDebug64 (
993 VOID
994 )
995 {
996 UINT32 Len;
997 EFI_IMAGE_OPTIONAL_HEADER_UNION *NtHdr;
998 EFI_IMAGE_DATA_DIRECTORY *DataDir;
999 EFI_IMAGE_DEBUG_DIRECTORY_ENTRY *Dir;
1000 EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY *Nb10;
1001
1002 Len = strlen(mInImageName) + 1;
1003
1004 Dir = (EFI_IMAGE_DEBUG_DIRECTORY_ENTRY*)(mCoffFile + mDebugOffset);
1005 Dir->Type = EFI_IMAGE_DEBUG_TYPE_CODEVIEW;
1006 Dir->SizeOfData = sizeof(EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY) + Len;
1007 Dir->RVA = mDebugOffset + sizeof(EFI_IMAGE_DEBUG_DIRECTORY_ENTRY);
1008 Dir->FileOffset = mDebugOffset + sizeof(EFI_IMAGE_DEBUG_DIRECTORY_ENTRY);
1009
1010 Nb10 = (EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY*)(Dir + 1);
1011 Nb10->Signature = CODEVIEW_SIGNATURE_NB10;
1012 strcpy ((char *)(Nb10 + 1), mInImageName);
1013
1014
1015 NtHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)(mCoffFile + mNtHdrOffset);
1016 DataDir = &NtHdr->Pe32Plus.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG];
1017 DataDir->VirtualAddress = mDebugOffset;
1018 DataDir->Size = Dir->SizeOfData + sizeof(EFI_IMAGE_DEBUG_DIRECTORY_ENTRY);
1019 }
1020
1021 STATIC
1022 VOID
1023 SetImageSize64 (
1024 VOID
1025 )
1026 {
1027 EFI_IMAGE_OPTIONAL_HEADER_UNION *NtHdr;
1028
1029 //
1030 // Set image size
1031 //
1032 NtHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)(mCoffFile + mNtHdrOffset);
1033 NtHdr->Pe32Plus.OptionalHeader.SizeOfImage = mCoffOffset;
1034 }
1035
1036 STATIC
1037 VOID
1038 CleanUp64 (
1039 VOID
1040 )
1041 {
1042 if (mCoffSectionsOffset != NULL) {
1043 free (mCoffSectionsOffset);
1044 }
1045 }
1046
1047