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