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