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