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