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