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