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