]> git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Source/C/GenFw/Elf32Convert.c
BaseTools GenFw: Support CLANG8ELF with conversion ELF to PE/COFF image
[mirror_edk2.git] / BaseTools / Source / C / GenFw / Elf32Convert.c
1 /** @file
2 Elf32 Convert solution
3
4 Copyright (c) 2010 - 2021, Intel Corporation. All rights reserved.<BR>
5 Portions copyright (c) 2013, ARM Ltd. All rights reserved.<BR>
6 Portions Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.<BR>
7
8 SPDX-License-Identifier: BSD-2-Clause-Patent
9
10 **/
11
12 #include "WinNtInclude.h"
13
14 #ifndef __GNUC__
15 #include <windows.h>
16 #include <io.h>
17 #endif
18 #include <assert.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <time.h>
23 #include <ctype.h>
24
25 #include <Common/UefiBaseTypes.h>
26 #include <IndustryStandard/PeImage.h>
27
28 #include "PeCoffLib.h"
29 #include "EfiUtilityMsgs.h"
30
31 #include "GenFw.h"
32 #include "ElfConvert.h"
33 #include "Elf32Convert.h"
34
35 STATIC
36 VOID
37 ScanSections32 (
38 VOID
39 );
40
41 STATIC
42 BOOLEAN
43 WriteSections32 (
44 SECTION_FILTER_TYPES FilterType
45 );
46
47 STATIC
48 VOID
49 WriteRelocations32 (
50 VOID
51 );
52
53 STATIC
54 VOID
55 WriteDebug32 (
56 VOID
57 );
58
59 STATIC
60 VOID
61 SetImageSize32 (
62 VOID
63 );
64
65 STATIC
66 VOID
67 CleanUp32 (
68 VOID
69 );
70
71 //
72 // Rename ELF32 structures to common names to help when porting to ELF64.
73 //
74 typedef Elf32_Shdr Elf_Shdr;
75 typedef Elf32_Ehdr Elf_Ehdr;
76 typedef Elf32_Rel Elf_Rel;
77 typedef Elf32_Sym Elf_Sym;
78 typedef Elf32_Phdr Elf_Phdr;
79 typedef Elf32_Dyn Elf_Dyn;
80 #define ELFCLASS ELFCLASS32
81 #define ELF_R_TYPE(r) ELF32_R_TYPE(r)
82 #define ELF_R_SYM(r) ELF32_R_SYM(r)
83
84 //
85 // Well known ELF structures.
86 //
87 STATIC Elf_Ehdr *mEhdr;
88 STATIC Elf_Shdr *mShdrBase;
89 STATIC Elf_Phdr *mPhdrBase;
90
91 //
92 // Coff information
93 //
94 STATIC UINT32 mCoffAlignment = 0x20;
95
96 //
97 // PE section alignment.
98 //
99 STATIC const UINT16 mCoffNbrSections = 4;
100
101 //
102 // ELF sections to offset in Coff file.
103 //
104 STATIC UINT32 *mCoffSectionsOffset = NULL;
105
106 //
107 // Offsets in COFF file
108 //
109 STATIC UINT32 mNtHdrOffset;
110 STATIC UINT32 mTextOffset;
111 STATIC UINT32 mDataOffset;
112 STATIC UINT32 mHiiRsrcOffset;
113 STATIC UINT32 mRelocOffset;
114 STATIC UINT32 mDebugOffset;
115
116 //
117 // Initialization Function
118 //
119 BOOLEAN
120 InitializeElf32 (
121 UINT8 *FileBuffer,
122 ELF_FUNCTION_TABLE *ElfFunctions
123 )
124 {
125 //
126 // Initialize data pointer and structures.
127 //
128 mEhdr = (Elf_Ehdr*) FileBuffer;
129
130 //
131 // Check the ELF32 specific header information.
132 //
133 if (mEhdr->e_ident[EI_CLASS] != ELFCLASS32) {
134 Error (NULL, 0, 3000, "Unsupported", "ELF EI_DATA not ELFCLASS32");
135 return FALSE;
136 }
137 if (mEhdr->e_ident[EI_DATA] != ELFDATA2LSB) {
138 Error (NULL, 0, 3000, "Unsupported", "ELF EI_DATA not ELFDATA2LSB");
139 return FALSE;
140 }
141 if ((mEhdr->e_type != ET_EXEC) && (mEhdr->e_type != ET_DYN)) {
142 Error (NULL, 0, 3000, "Unsupported", "ELF e_type not ET_EXEC or ET_DYN");
143 return FALSE;
144 }
145 if (!((mEhdr->e_machine == EM_386) || (mEhdr->e_machine == EM_ARM) || (mEhdr->e_machine == EM_RISCV))) {
146 Warning (NULL, 0, 3000, "Unsupported", "ELF e_machine is not Elf32 machine.");
147 }
148 if (mEhdr->e_version != EV_CURRENT) {
149 Error (NULL, 0, 3000, "Unsupported", "ELF e_version (%u) not EV_CURRENT (%d)", (unsigned) mEhdr->e_version, EV_CURRENT);
150 return FALSE;
151 }
152
153 //
154 // Update section header pointers
155 //
156 mShdrBase = (Elf_Shdr *)((UINT8 *)mEhdr + mEhdr->e_shoff);
157 mPhdrBase = (Elf_Phdr *)((UINT8 *)mEhdr + mEhdr->e_phoff);
158
159 //
160 // Create COFF Section offset buffer and zero.
161 //
162 mCoffSectionsOffset = (UINT32 *)malloc(mEhdr->e_shnum * sizeof (UINT32));
163 if (mCoffSectionsOffset == NULL) {
164 Error (NULL, 0, 4001, "Resource", "memory cannot be allocated!");
165 return FALSE;
166 }
167 memset(mCoffSectionsOffset, 0, mEhdr->e_shnum * sizeof(UINT32));
168
169 //
170 // Fill in function pointers.
171 //
172 ElfFunctions->ScanSections = ScanSections32;
173 ElfFunctions->WriteSections = WriteSections32;
174 ElfFunctions->WriteRelocations = WriteRelocations32;
175 ElfFunctions->WriteDebug = WriteDebug32;
176 ElfFunctions->SetImageSize = SetImageSize32;
177 ElfFunctions->CleanUp = CleanUp32;
178
179 return TRUE;
180 }
181
182
183 //
184 // Header by Index functions
185 //
186 STATIC
187 Elf_Shdr*
188 GetShdrByIndex (
189 UINT32 Num
190 )
191 {
192 if (Num >= mEhdr->e_shnum) {
193 Error (NULL, 0, 3000, "Invalid", "GetShdrByIndex: Index %u is too high.", Num);
194 exit(EXIT_FAILURE);
195 }
196
197 return (Elf_Shdr*)((UINT8*)mShdrBase + Num * mEhdr->e_shentsize);
198 }
199
200 STATIC
201 Elf_Phdr*
202 GetPhdrByIndex (
203 UINT32 num
204 )
205 {
206 if (num >= mEhdr->e_phnum) {
207 Error (NULL, 0, 3000, "Invalid", "GetPhdrByIndex: Index %u is too high.", num);
208 exit(EXIT_FAILURE);
209 }
210
211 return (Elf_Phdr *)((UINT8*)mPhdrBase + num * mEhdr->e_phentsize);
212 }
213
214 STATIC
215 UINT32
216 CoffAlign (
217 UINT32 Offset
218 )
219 {
220 return (Offset + mCoffAlignment - 1) & ~(mCoffAlignment - 1);
221 }
222
223 STATIC
224 UINT32
225 DebugRvaAlign (
226 UINT32 Offset
227 )
228 {
229 return (Offset + 3) & ~3;
230 }
231
232 //
233 // filter functions
234 //
235 STATIC
236 BOOLEAN
237 IsTextShdr (
238 Elf_Shdr *Shdr
239 )
240 {
241 return (BOOLEAN) ((Shdr->sh_flags & (SHF_EXECINSTR | SHF_ALLOC)) == (SHF_EXECINSTR | SHF_ALLOC));
242 }
243
244 STATIC
245 BOOLEAN
246 IsHiiRsrcShdr (
247 Elf_Shdr *Shdr
248 )
249 {
250 Elf_Shdr *Namedr = GetShdrByIndex(mEhdr->e_shstrndx);
251
252 return (BOOLEAN) (strcmp((CHAR8*)mEhdr + Namedr->sh_offset + Shdr->sh_name, ELF_HII_SECTION_NAME) == 0);
253 }
254
255 STATIC
256 BOOLEAN
257 IsDataShdr (
258 Elf_Shdr *Shdr
259 )
260 {
261 if (IsHiiRsrcShdr(Shdr)) {
262 return FALSE;
263 }
264 return (BOOLEAN) (Shdr->sh_flags & (SHF_EXECINSTR | SHF_WRITE | SHF_ALLOC)) == (SHF_ALLOC | SHF_WRITE);
265 }
266
267 STATIC
268 BOOLEAN
269 IsStrtabShdr (
270 Elf_Shdr *Shdr
271 )
272 {
273 Elf_Shdr *Namedr = GetShdrByIndex(mEhdr->e_shstrndx);
274
275 return (BOOLEAN) (strcmp((CHAR8*)mEhdr + Namedr->sh_offset + Shdr->sh_name, ELF_STRTAB_SECTION_NAME) == 0);
276 }
277
278 STATIC
279 Elf_Shdr *
280 FindStrtabShdr (
281 VOID
282 )
283 {
284 UINT32 i;
285 for (i = 0; i < mEhdr->e_shnum; i++) {
286 Elf_Shdr *shdr = GetShdrByIndex(i);
287 if (IsStrtabShdr(shdr)) {
288 return shdr;
289 }
290 }
291 return NULL;
292 }
293
294 STATIC
295 const UINT8 *
296 GetSymName (
297 Elf_Sym *Sym
298 )
299 {
300 Elf_Shdr *StrtabShdr;
301 UINT8 *StrtabContents;
302 BOOLEAN foundEnd;
303 UINT32 i;
304
305 if (Sym->st_name == 0) {
306 return NULL;
307 }
308
309 StrtabShdr = FindStrtabShdr();
310 if (StrtabShdr == NULL) {
311 return NULL;
312 }
313
314 assert(Sym->st_name < StrtabShdr->sh_size);
315
316 StrtabContents = (UINT8*)mEhdr + StrtabShdr->sh_offset;
317
318 foundEnd = FALSE;
319 for (i = Sym->st_name; (i < StrtabShdr->sh_size) && !foundEnd; i++) {
320 foundEnd = (BOOLEAN)(StrtabContents[i] == 0);
321 }
322 assert(foundEnd);
323
324 return StrtabContents + Sym->st_name;
325 }
326
327 //
328 // Elf functions interface implementation
329 //
330
331 STATIC
332 VOID
333 ScanSections32 (
334 VOID
335 )
336 {
337 UINT32 i;
338 EFI_IMAGE_DOS_HEADER *DosHdr;
339 EFI_IMAGE_OPTIONAL_HEADER_UNION *NtHdr;
340 UINT32 CoffEntry;
341 UINT32 SectionCount;
342 BOOLEAN FoundSection;
343
344 CoffEntry = 0;
345 mCoffOffset = 0;
346
347 //
348 // Coff file start with a DOS header.
349 //
350 mCoffOffset = sizeof(EFI_IMAGE_DOS_HEADER) + 0x40;
351 mNtHdrOffset = mCoffOffset;
352 switch (mEhdr->e_machine) {
353 case EM_386:
354 case EM_ARM:
355 mCoffOffset += sizeof (EFI_IMAGE_NT_HEADERS32);
356 break;
357 default:
358 VerboseMsg ("%s unknown e_machine type. Assume IA-32", (UINTN)mEhdr->e_machine);
359 mCoffOffset += sizeof (EFI_IMAGE_NT_HEADERS32);
360 break;
361 }
362
363 mTableOffset = mCoffOffset;
364 mCoffOffset += mCoffNbrSections * sizeof(EFI_IMAGE_SECTION_HEADER);
365
366 //
367 // Set mCoffAlignment to the maximum alignment of the input sections
368 // we care about
369 //
370 for (i = 0; i < mEhdr->e_shnum; i++) {
371 Elf_Shdr *shdr = GetShdrByIndex(i);
372 if (shdr->sh_addralign <= mCoffAlignment) {
373 continue;
374 }
375 if (IsTextShdr(shdr) || IsDataShdr(shdr) || IsHiiRsrcShdr(shdr)) {
376 mCoffAlignment = (UINT32)shdr->sh_addralign;
377 }
378 }
379
380 //
381 // Check if mCoffAlignment is larger than MAX_COFF_ALIGNMENT
382 //
383 if (mCoffAlignment > MAX_COFF_ALIGNMENT) {
384 Error (NULL, 0, 3000, "Invalid", "Section alignment is larger than MAX_COFF_ALIGNMENT.");
385 assert (FALSE);
386 }
387
388 //
389 // Move the PE/COFF header right before the first section. This will help us
390 // save space when converting to TE.
391 //
392 if (mCoffAlignment > mCoffOffset) {
393 mNtHdrOffset += mCoffAlignment - mCoffOffset;
394 mTableOffset += mCoffAlignment - mCoffOffset;
395 mCoffOffset = mCoffAlignment;
396 }
397
398 //
399 // First text sections.
400 //
401 mCoffOffset = CoffAlign(mCoffOffset);
402 mTextOffset = mCoffOffset;
403 FoundSection = FALSE;
404 SectionCount = 0;
405 for (i = 0; i < mEhdr->e_shnum; i++) {
406 Elf_Shdr *shdr = GetShdrByIndex(i);
407 if (IsTextShdr(shdr)) {
408 if ((shdr->sh_addralign != 0) && (shdr->sh_addralign != 1)) {
409 // the alignment field is valid
410 if ((shdr->sh_addr & (shdr->sh_addralign - 1)) == 0) {
411 // if the section address is aligned we must align PE/COFF
412 mCoffOffset = (mCoffOffset + shdr->sh_addralign - 1) & ~(shdr->sh_addralign - 1);
413 } else {
414 Error (NULL, 0, 3000, "Invalid", "Section address not aligned to its own alignment.");
415 }
416 }
417
418 /* Relocate entry. */
419 if ((mEhdr->e_entry >= shdr->sh_addr) &&
420 (mEhdr->e_entry < shdr->sh_addr + shdr->sh_size)) {
421 CoffEntry = mCoffOffset + mEhdr->e_entry - shdr->sh_addr;
422 }
423
424 //
425 // Set mTextOffset with the offset of the first '.text' section
426 //
427 if (!FoundSection) {
428 mTextOffset = mCoffOffset;
429 FoundSection = TRUE;
430 }
431
432 mCoffSectionsOffset[i] = mCoffOffset;
433 mCoffOffset += shdr->sh_size;
434 SectionCount ++;
435 }
436 }
437
438 if (!FoundSection) {
439 Error (NULL, 0, 3000, "Invalid", "Did not find any '.text' section.");
440 assert (FALSE);
441 }
442
443 mDebugOffset = DebugRvaAlign(mCoffOffset);
444 mCoffOffset = CoffAlign(mCoffOffset);
445
446 if (SectionCount > 1 && mOutImageType == FW_EFI_IMAGE) {
447 Warning (NULL, 0, 0, NULL, "Multiple sections in %s are merged into 1 text section. Source level debug might not work correctly.", mInImageName);
448 }
449
450 //
451 // Then data sections.
452 //
453 mDataOffset = mCoffOffset;
454 FoundSection = FALSE;
455 SectionCount = 0;
456 for (i = 0; i < mEhdr->e_shnum; i++) {
457 Elf_Shdr *shdr = GetShdrByIndex(i);
458 if (IsDataShdr(shdr)) {
459 if ((shdr->sh_addralign != 0) && (shdr->sh_addralign != 1)) {
460 // the alignment field is valid
461 if ((shdr->sh_addr & (shdr->sh_addralign - 1)) == 0) {
462 // if the section address is aligned we must align PE/COFF
463 mCoffOffset = (mCoffOffset + shdr->sh_addralign - 1) & ~(shdr->sh_addralign - 1);
464 } else {
465 Error (NULL, 0, 3000, "Invalid", "Section address not aligned to its own alignment.");
466 }
467 }
468
469 //
470 // Set mDataOffset with the offset of the first '.data' section
471 //
472 if (!FoundSection) {
473 mDataOffset = mCoffOffset;
474 FoundSection = TRUE;
475 }
476
477 mCoffSectionsOffset[i] = mCoffOffset;
478 mCoffOffset += shdr->sh_size;
479 SectionCount ++;
480 }
481 }
482
483 if (SectionCount > 1 && mOutImageType == FW_EFI_IMAGE) {
484 Warning (NULL, 0, 0, NULL, "Multiple sections in %s are merged into 1 data section. Source level debug might not work correctly.", mInImageName);
485 }
486
487 //
488 // Make room for .debug data in .data (or .text if .data is empty) instead of
489 // putting it in a section of its own. This is explicitly allowed by the
490 // PE/COFF spec, and prevents bloat in the binary when using large values for
491 // section alignment.
492 //
493 if (SectionCount > 0) {
494 mDebugOffset = DebugRvaAlign(mCoffOffset);
495 }
496 mCoffOffset = mDebugOffset + sizeof(EFI_IMAGE_DEBUG_DIRECTORY_ENTRY) +
497 sizeof(EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY) +
498 strlen(mInImageName) + 1;
499
500 mCoffOffset = CoffAlign(mCoffOffset);
501 if (SectionCount == 0) {
502 mDataOffset = mCoffOffset;
503 }
504
505 //
506 // The HII resource sections.
507 //
508 mHiiRsrcOffset = mCoffOffset;
509 for (i = 0; i < mEhdr->e_shnum; i++) {
510 Elf_Shdr *shdr = GetShdrByIndex(i);
511 if (IsHiiRsrcShdr(shdr)) {
512 if ((shdr->sh_addralign != 0) && (shdr->sh_addralign != 1)) {
513 // the alignment field is valid
514 if ((shdr->sh_addr & (shdr->sh_addralign - 1)) == 0) {
515 // if the section address is aligned we must align PE/COFF
516 mCoffOffset = (mCoffOffset + shdr->sh_addralign - 1) & ~(shdr->sh_addralign - 1);
517 } else {
518 Error (NULL, 0, 3000, "Invalid", "Section address not aligned to its own alignment.");
519 }
520 }
521 if (shdr->sh_size != 0) {
522 mHiiRsrcOffset = mCoffOffset;
523 mCoffSectionsOffset[i] = mCoffOffset;
524 mCoffOffset += shdr->sh_size;
525 mCoffOffset = CoffAlign(mCoffOffset);
526 SetHiiResourceHeader ((UINT8*) mEhdr + shdr->sh_offset, mHiiRsrcOffset);
527 }
528 break;
529 }
530 }
531
532 mRelocOffset = mCoffOffset;
533
534 //
535 // Allocate base Coff file. Will be expanded later for relocations.
536 //
537 mCoffFile = (UINT8 *)malloc(mCoffOffset);
538 if (mCoffFile == NULL) {
539 Error (NULL, 0, 4001, "Resource", "memory cannot be allocated!");
540 }
541 assert (mCoffFile != NULL);
542 memset(mCoffFile, 0, mCoffOffset);
543
544 //
545 // Fill headers.
546 //
547 DosHdr = (EFI_IMAGE_DOS_HEADER *)mCoffFile;
548 DosHdr->e_magic = EFI_IMAGE_DOS_SIGNATURE;
549 DosHdr->e_lfanew = mNtHdrOffset;
550
551 NtHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION*)(mCoffFile + mNtHdrOffset);
552
553 NtHdr->Pe32.Signature = EFI_IMAGE_NT_SIGNATURE;
554
555 switch (mEhdr->e_machine) {
556 case EM_386:
557 NtHdr->Pe32.FileHeader.Machine = EFI_IMAGE_MACHINE_IA32;
558 NtHdr->Pe32.OptionalHeader.Magic = EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC;
559 break;
560 case EM_ARM:
561 NtHdr->Pe32.FileHeader.Machine = EFI_IMAGE_MACHINE_ARMT;
562 NtHdr->Pe32.OptionalHeader.Magic = EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC;
563 break;
564 default:
565 VerboseMsg ("%s unknown e_machine type %hu. Assume IA-32", mInImageName, mEhdr->e_machine);
566 NtHdr->Pe32.FileHeader.Machine = EFI_IMAGE_MACHINE_IA32;
567 NtHdr->Pe32.OptionalHeader.Magic = EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC;
568 }
569
570 NtHdr->Pe32.FileHeader.NumberOfSections = mCoffNbrSections;
571 NtHdr->Pe32.FileHeader.TimeDateStamp = (UINT32) time(NULL);
572 mImageTimeStamp = NtHdr->Pe32.FileHeader.TimeDateStamp;
573 NtHdr->Pe32.FileHeader.PointerToSymbolTable = 0;
574 NtHdr->Pe32.FileHeader.NumberOfSymbols = 0;
575 NtHdr->Pe32.FileHeader.SizeOfOptionalHeader = sizeof(NtHdr->Pe32.OptionalHeader);
576 NtHdr->Pe32.FileHeader.Characteristics = EFI_IMAGE_FILE_EXECUTABLE_IMAGE
577 | EFI_IMAGE_FILE_LINE_NUMS_STRIPPED
578 | EFI_IMAGE_FILE_LOCAL_SYMS_STRIPPED
579 | EFI_IMAGE_FILE_32BIT_MACHINE;
580
581 NtHdr->Pe32.OptionalHeader.SizeOfCode = mDataOffset - mTextOffset;
582 NtHdr->Pe32.OptionalHeader.SizeOfInitializedData = mRelocOffset - mDataOffset;
583 NtHdr->Pe32.OptionalHeader.SizeOfUninitializedData = 0;
584 NtHdr->Pe32.OptionalHeader.AddressOfEntryPoint = CoffEntry;
585
586 NtHdr->Pe32.OptionalHeader.BaseOfCode = mTextOffset;
587
588 NtHdr->Pe32.OptionalHeader.BaseOfData = mDataOffset;
589 NtHdr->Pe32.OptionalHeader.ImageBase = 0;
590 NtHdr->Pe32.OptionalHeader.SectionAlignment = mCoffAlignment;
591 NtHdr->Pe32.OptionalHeader.FileAlignment = mCoffAlignment;
592 NtHdr->Pe32.OptionalHeader.SizeOfImage = 0;
593
594 NtHdr->Pe32.OptionalHeader.SizeOfHeaders = mTextOffset;
595 NtHdr->Pe32.OptionalHeader.NumberOfRvaAndSizes = EFI_IMAGE_NUMBER_OF_DIRECTORY_ENTRIES;
596
597 //
598 // Section headers.
599 //
600 if ((mDataOffset - mTextOffset) > 0) {
601 CreateSectionHeader (".text", mTextOffset, mDataOffset - mTextOffset,
602 EFI_IMAGE_SCN_CNT_CODE
603 | EFI_IMAGE_SCN_MEM_EXECUTE
604 | EFI_IMAGE_SCN_MEM_READ);
605 } else {
606 // Don't make a section of size 0.
607 NtHdr->Pe32.FileHeader.NumberOfSections--;
608 }
609
610 if ((mHiiRsrcOffset - mDataOffset) > 0) {
611 CreateSectionHeader (".data", mDataOffset, mHiiRsrcOffset - mDataOffset,
612 EFI_IMAGE_SCN_CNT_INITIALIZED_DATA
613 | EFI_IMAGE_SCN_MEM_WRITE
614 | EFI_IMAGE_SCN_MEM_READ);
615 } else {
616 // Don't make a section of size 0.
617 NtHdr->Pe32.FileHeader.NumberOfSections--;
618 }
619
620 if ((mRelocOffset - mHiiRsrcOffset) > 0) {
621 CreateSectionHeader (".rsrc", mHiiRsrcOffset, mRelocOffset - mHiiRsrcOffset,
622 EFI_IMAGE_SCN_CNT_INITIALIZED_DATA
623 | EFI_IMAGE_SCN_MEM_READ);
624
625 NtHdr->Pe32.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE].Size = mRelocOffset - mHiiRsrcOffset;
626 NtHdr->Pe32.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress = mHiiRsrcOffset;
627 } else {
628 // Don't make a section of size 0.
629 NtHdr->Pe32.FileHeader.NumberOfSections--;
630 }
631
632 }
633
634 STATIC
635 BOOLEAN
636 WriteSections32 (
637 SECTION_FILTER_TYPES FilterType
638 )
639 {
640 UINT32 Idx;
641 Elf_Shdr *SecShdr;
642 UINT32 SecOffset;
643 BOOLEAN (*Filter)(Elf_Shdr *);
644
645 //
646 // Initialize filter pointer
647 //
648 switch (FilterType) {
649 case SECTION_TEXT:
650 Filter = IsTextShdr;
651 break;
652 case SECTION_HII:
653 Filter = IsHiiRsrcShdr;
654 break;
655 case SECTION_DATA:
656 Filter = IsDataShdr;
657 break;
658 default:
659 return FALSE;
660 }
661
662 //
663 // First: copy sections.
664 //
665 for (Idx = 0; Idx < mEhdr->e_shnum; Idx++) {
666 Elf_Shdr *Shdr = GetShdrByIndex(Idx);
667 if ((*Filter)(Shdr)) {
668 switch (Shdr->sh_type) {
669 case SHT_PROGBITS:
670 /* Copy. */
671 if (Shdr->sh_offset + Shdr->sh_size > mFileBufferSize) {
672 return FALSE;
673 }
674 memcpy(mCoffFile + mCoffSectionsOffset[Idx],
675 (UINT8*)mEhdr + Shdr->sh_offset,
676 Shdr->sh_size);
677 break;
678
679 case SHT_NOBITS:
680 memset(mCoffFile + mCoffSectionsOffset[Idx], 0, Shdr->sh_size);
681 break;
682
683 default:
684 //
685 // Ignore for unknown section type.
686 //
687 VerboseMsg ("%s unknown section type %x. We ignore this unknown section type.", mInImageName, (unsigned)Shdr->sh_type);
688 break;
689 }
690 }
691 }
692
693 //
694 // Second: apply relocations.
695 //
696 for (Idx = 0; Idx < mEhdr->e_shnum; Idx++) {
697 //
698 // Determine if this is a relocation section.
699 //
700 Elf_Shdr *RelShdr = GetShdrByIndex(Idx);
701 if ((RelShdr->sh_type != SHT_REL) && (RelShdr->sh_type != SHT_RELA)) {
702 continue;
703 }
704
705 //
706 // Relocation section found. Now extract section information that the relocations
707 // apply to in the ELF data and the new COFF data.
708 //
709 SecShdr = GetShdrByIndex(RelShdr->sh_info);
710 SecOffset = mCoffSectionsOffset[RelShdr->sh_info];
711
712 //
713 // Only process relocations for the current filter type.
714 //
715 if (RelShdr->sh_type == SHT_REL && (*Filter)(SecShdr)) {
716 UINT32 RelOffset;
717
718 //
719 // Determine the symbol table referenced by the relocation data.
720 //
721 Elf_Shdr *SymtabShdr = GetShdrByIndex(RelShdr->sh_link);
722 UINT8 *Symtab = (UINT8*)mEhdr + SymtabShdr->sh_offset;
723
724 //
725 // Process all relocation entries for this section.
726 //
727 for (RelOffset = 0; RelOffset < RelShdr->sh_size; RelOffset += RelShdr->sh_entsize) {
728 //
729 // Set pointer to relocation entry
730 //
731 Elf_Rel *Rel = (Elf_Rel *)((UINT8*)mEhdr + RelShdr->sh_offset + RelOffset);
732
733 //
734 // Set pointer to symbol table entry associated with the relocation entry.
735 //
736 Elf_Sym *Sym = (Elf_Sym *)(Symtab + ELF_R_SYM(Rel->r_info) * SymtabShdr->sh_entsize);
737
738 Elf_Shdr *SymShdr;
739 UINT8 *Targ;
740 UINT16 Address;
741
742 //
743 // Check section header index found in symbol table and get the section
744 // header location.
745 //
746 if (Sym->st_shndx == SHN_UNDEF
747 || Sym->st_shndx >= mEhdr->e_shnum) {
748 const UINT8 *SymName = GetSymName(Sym);
749 if (SymName == NULL) {
750 SymName = (const UINT8 *)"<unknown>";
751 }
752 continue;
753 }
754 SymShdr = GetShdrByIndex(Sym->st_shndx);
755
756 //
757 // Convert the relocation data to a pointer into the coff file.
758 //
759 // Note:
760 // r_offset is the virtual address of the storage unit to be relocated.
761 // sh_addr is the virtual address for the base of the section.
762 //
763 Targ = mCoffFile + SecOffset + (Rel->r_offset - SecShdr->sh_addr);
764
765 //
766 // Determine how to handle each relocation type based on the machine type.
767 //
768 if (mEhdr->e_machine == EM_386) {
769 switch (ELF_R_TYPE(Rel->r_info)) {
770 case R_386_NONE:
771 break;
772 case R_386_32:
773 //
774 // Absolute relocation.
775 // Converts Targ from a absolute virtual address to the absolute
776 // COFF address.
777 //
778 *(UINT32 *)Targ = *(UINT32 *)Targ - SymShdr->sh_addr
779 + mCoffSectionsOffset[Sym->st_shndx];
780 break;
781 case R_386_PC32:
782 //
783 // Relative relocation: Symbol - Ip + Addend
784 //
785 *(UINT32 *)Targ = *(UINT32 *)Targ
786 + (mCoffSectionsOffset[Sym->st_shndx] - SymShdr->sh_addr)
787 - (SecOffset - SecShdr->sh_addr);
788 break;
789 default:
790 Error (NULL, 0, 3000, "Invalid", "%s unsupported ELF EM_386 relocation 0x%x.", mInImageName, (unsigned) ELF_R_TYPE(Rel->r_info));
791 }
792 } else if (mEhdr->e_machine == EM_ARM) {
793 switch (ELF32_R_TYPE(Rel->r_info)) {
794 case R_ARM_RBASE:
795 // No relocation - no action required
796 // break skipped
797
798 case R_ARM_PC24:
799 case R_ARM_REL32:
800 case R_ARM_XPC25:
801 case R_ARM_THM_PC22:
802 case R_ARM_THM_JUMP19:
803 case R_ARM_CALL:
804 case R_ARM_JMP24:
805 case R_ARM_THM_JUMP24:
806 case R_ARM_PREL31:
807 case R_ARM_MOVW_PREL_NC:
808 case R_ARM_MOVT_PREL:
809 case R_ARM_THM_MOVW_PREL_NC:
810 case R_ARM_THM_MOVT_PREL:
811 case R_ARM_THM_JMP6:
812 case R_ARM_THM_ALU_PREL_11_0:
813 case R_ARM_THM_PC12:
814 case R_ARM_REL32_NOI:
815 case R_ARM_ALU_PC_G0_NC:
816 case R_ARM_ALU_PC_G0:
817 case R_ARM_ALU_PC_G1_NC:
818 case R_ARM_ALU_PC_G1:
819 case R_ARM_ALU_PC_G2:
820 case R_ARM_LDR_PC_G1:
821 case R_ARM_LDR_PC_G2:
822 case R_ARM_LDRS_PC_G0:
823 case R_ARM_LDRS_PC_G1:
824 case R_ARM_LDRS_PC_G2:
825 case R_ARM_LDC_PC_G0:
826 case R_ARM_LDC_PC_G1:
827 case R_ARM_LDC_PC_G2:
828 case R_ARM_THM_JUMP11:
829 case R_ARM_THM_JUMP8:
830 case R_ARM_TLS_GD32:
831 case R_ARM_TLS_LDM32:
832 case R_ARM_TLS_IE32:
833 // Thease are all PC-relative relocations and don't require modification
834 // GCC does not seem to have the concept of a application that just needs to get relocated.
835 break;
836
837 case R_ARM_THM_MOVW_ABS_NC:
838 // MOVW is only lower 16-bits of the addres
839 Address = (UINT16)(Sym->st_value - SymShdr->sh_addr + mCoffSectionsOffset[Sym->st_shndx]);
840 ThumbMovtImmediatePatch ((UINT16 *)Targ, Address);
841 break;
842
843 case R_ARM_THM_MOVT_ABS:
844 // MOVT is only upper 16-bits of the addres
845 Address = (UINT16)((Sym->st_value - SymShdr->sh_addr + mCoffSectionsOffset[Sym->st_shndx]) >> 16);
846 ThumbMovtImmediatePatch ((UINT16 *)Targ, Address);
847 break;
848
849 case R_ARM_ABS32:
850 case R_ARM_RABS32:
851 //
852 // Absolute relocation.
853 //
854 *(UINT32 *)Targ = *(UINT32 *)Targ - SymShdr->sh_addr + mCoffSectionsOffset[Sym->st_shndx];
855 break;
856
857 default:
858 Error (NULL, 0, 3000, "Invalid", "WriteSections (): %s unsupported ELF EM_ARM relocation 0x%x.", mInImageName, (unsigned) ELF32_R_TYPE(Rel->r_info));
859 }
860 }
861 }
862 }
863 }
864
865 return TRUE;
866 }
867
868 UINTN gMovwOffset = 0;
869
870 STATIC
871 VOID
872 WriteRelocations32 (
873 VOID
874 )
875 {
876 UINT32 Index;
877 EFI_IMAGE_OPTIONAL_HEADER_UNION *NtHdr;
878 EFI_IMAGE_DATA_DIRECTORY *Dir;
879 BOOLEAN FoundRelocations;
880 Elf_Dyn *Dyn;
881 Elf_Rel *Rel;
882 UINTN RelElementSize;
883 UINTN RelSize;
884 UINTN RelOffset;
885 UINTN K;
886 Elf32_Phdr *DynamicSegment;
887
888 for (Index = 0, FoundRelocations = FALSE; Index < mEhdr->e_shnum; Index++) {
889 Elf_Shdr *RelShdr = GetShdrByIndex(Index);
890 if ((RelShdr->sh_type == SHT_REL) || (RelShdr->sh_type == SHT_RELA)) {
891 Elf_Shdr *SecShdr = GetShdrByIndex (RelShdr->sh_info);
892 if (IsTextShdr(SecShdr) || IsDataShdr(SecShdr)) {
893 UINT32 RelIdx;
894
895 FoundRelocations = TRUE;
896 for (RelIdx = 0; RelIdx < RelShdr->sh_size; RelIdx += RelShdr->sh_entsize) {
897 Rel = (Elf_Rel *)((UINT8*)mEhdr + RelShdr->sh_offset + RelIdx);
898
899 if (mEhdr->e_machine == EM_386) {
900 switch (ELF_R_TYPE(Rel->r_info)) {
901 case R_386_NONE:
902 case R_386_PC32:
903 //
904 // No fixup entry required.
905 //
906 break;
907 case R_386_32:
908 //
909 // Creates a relative relocation entry from the absolute entry.
910 //
911 CoffAddFixup(mCoffSectionsOffset[RelShdr->sh_info]
912 + (Rel->r_offset - SecShdr->sh_addr),
913 EFI_IMAGE_REL_BASED_HIGHLOW);
914 break;
915 default:
916 Error (NULL, 0, 3000, "Invalid", "%s unsupported ELF EM_386 relocation 0x%x.", mInImageName, (unsigned) ELF_R_TYPE(Rel->r_info));
917 }
918 } else if (mEhdr->e_machine == EM_ARM) {
919 switch (ELF32_R_TYPE(Rel->r_info)) {
920 case R_ARM_RBASE:
921 // No relocation - no action required
922 // break skipped
923
924 case R_ARM_PC24:
925 case R_ARM_REL32:
926 case R_ARM_XPC25:
927 case R_ARM_THM_PC22:
928 case R_ARM_THM_JUMP19:
929 case R_ARM_CALL:
930 case R_ARM_JMP24:
931 case R_ARM_THM_JUMP24:
932 case R_ARM_PREL31:
933 case R_ARM_MOVW_PREL_NC:
934 case R_ARM_MOVT_PREL:
935 case R_ARM_THM_MOVW_PREL_NC:
936 case R_ARM_THM_MOVT_PREL:
937 case R_ARM_THM_JMP6:
938 case R_ARM_THM_ALU_PREL_11_0:
939 case R_ARM_THM_PC12:
940 case R_ARM_REL32_NOI:
941 case R_ARM_ALU_PC_G0_NC:
942 case R_ARM_ALU_PC_G0:
943 case R_ARM_ALU_PC_G1_NC:
944 case R_ARM_ALU_PC_G1:
945 case R_ARM_ALU_PC_G2:
946 case R_ARM_LDR_PC_G1:
947 case R_ARM_LDR_PC_G2:
948 case R_ARM_LDRS_PC_G0:
949 case R_ARM_LDRS_PC_G1:
950 case R_ARM_LDRS_PC_G2:
951 case R_ARM_LDC_PC_G0:
952 case R_ARM_LDC_PC_G1:
953 case R_ARM_LDC_PC_G2:
954 case R_ARM_THM_JUMP11:
955 case R_ARM_THM_JUMP8:
956 case R_ARM_TLS_GD32:
957 case R_ARM_TLS_LDM32:
958 case R_ARM_TLS_IE32:
959 // Thease are all PC-relative relocations and don't require modification
960 break;
961
962 case R_ARM_THM_MOVW_ABS_NC:
963 CoffAddFixup (
964 mCoffSectionsOffset[RelShdr->sh_info]
965 + (Rel->r_offset - SecShdr->sh_addr),
966 EFI_IMAGE_REL_BASED_ARM_MOV32T
967 );
968
969 // PE/COFF treats MOVW/MOVT relocation as single 64-bit instruction
970 // Track this address so we can log an error for unsupported sequence of MOVW/MOVT
971 gMovwOffset = mCoffSectionsOffset[RelShdr->sh_info] + (Rel->r_offset - SecShdr->sh_addr);
972 break;
973
974 case R_ARM_THM_MOVT_ABS:
975 if ((gMovwOffset + 4) != (mCoffSectionsOffset[RelShdr->sh_info] + (Rel->r_offset - SecShdr->sh_addr))) {
976 Error (NULL, 0, 3000, "Not Supported", "PE/COFF requires MOVW+MOVT instruction sequence %x +4 != %x.", gMovwOffset, mCoffSectionsOffset[RelShdr->sh_info] + (Rel->r_offset - SecShdr->sh_addr));
977 }
978 break;
979
980 case R_ARM_ABS32:
981 case R_ARM_RABS32:
982 CoffAddFixup (
983 mCoffSectionsOffset[RelShdr->sh_info]
984 + (Rel->r_offset - SecShdr->sh_addr),
985 EFI_IMAGE_REL_BASED_HIGHLOW
986 );
987 break;
988
989 default:
990 Error (NULL, 0, 3000, "Invalid", "WriteRelocations(): %s unsupported ELF EM_ARM relocation 0x%x.", mInImageName, (unsigned) ELF32_R_TYPE(Rel->r_info));
991 }
992 } else {
993 Error (NULL, 0, 3000, "Not Supported", "This tool does not support relocations for ELF with e_machine %u (processor type).", (unsigned) mEhdr->e_machine);
994 }
995 }
996 }
997 }
998 }
999
1000 if (!FoundRelocations && (mEhdr->e_machine == EM_ARM)) {
1001 /* Try again, but look for PT_DYNAMIC instead of SHT_REL */
1002
1003 for (Index = 0; Index < mEhdr->e_phnum; Index++) {
1004 RelElementSize = 0;
1005 RelSize = 0;
1006 RelOffset = 0;
1007
1008 DynamicSegment = GetPhdrByIndex (Index);
1009
1010 if (DynamicSegment->p_type == PT_DYNAMIC) {
1011 Dyn = (Elf32_Dyn *) ((UINT8 *)mEhdr + DynamicSegment->p_offset);
1012
1013 while (Dyn->d_tag != DT_NULL) {
1014 switch (Dyn->d_tag) {
1015 case DT_REL:
1016 RelOffset = Dyn->d_un.d_val;
1017 break;
1018
1019 case DT_RELSZ:
1020 RelSize = Dyn->d_un.d_val;
1021 break;
1022
1023 case DT_RELENT:
1024 RelElementSize = Dyn->d_un.d_val;
1025 break;
1026
1027 default:
1028 break;
1029 }
1030 Dyn++;
1031 }
1032 if (( RelOffset == 0 ) || ( RelSize == 0 ) || ( RelElementSize == 0 )) {
1033 Error (NULL, 0, 3000, "Invalid", "%s bad ARM dynamic relocations.", mInImageName);
1034 }
1035
1036 for (Index = 0; Index < mEhdr->e_shnum; Index++) {
1037 Elf_Shdr *shdr = GetShdrByIndex(Index);
1038
1039 //
1040 // The PT_DYNAMIC section contains DT_REL relocations whose r_offset
1041 // field is relative to the base of a segment (or the entire image),
1042 // and not to the base of an ELF input section as is the case for
1043 // SHT_REL sections. This means that we cannot fix up such relocations
1044 // unless we cross-reference ELF sections and segments, considering
1045 // that the output placement recorded in mCoffSectionsOffset[] is
1046 // section based, not segment based.
1047 //
1048 // Fortunately, there is a simple way around this: we require that the
1049 // in-memory layout of the ELF and PE/COFF versions of the binary is
1050 // identical. That way, r_offset will retain its validity as a PE/COFF
1051 // image offset, and we can record it in the COFF fixup table
1052 // unmodified.
1053 //
1054 if (shdr->sh_addr != mCoffSectionsOffset[Index]) {
1055 Error (NULL, 0, 3000,
1056 "Invalid", "%s: PT_DYNAMIC relocations require identical ELF and PE/COFF section offsets.",
1057 mInImageName);
1058 }
1059 }
1060
1061 for (K = 0; K < RelSize; K += RelElementSize) {
1062
1063 if (DynamicSegment->p_paddr == 0) {
1064 // Older versions of the ARM ELF (SWS ESPC 0003 B-02) specification define DT_REL
1065 // as an offset in the dynamic segment. p_paddr is defined to be zero for ARM tools
1066 Rel = (Elf32_Rel *) ((UINT8 *) mEhdr + DynamicSegment->p_offset + RelOffset + K);
1067 } else {
1068 // This is how it reads in the generic ELF specification
1069 Rel = (Elf32_Rel *) ((UINT8 *) mEhdr + RelOffset + K);
1070 }
1071
1072 switch (ELF32_R_TYPE (Rel->r_info)) {
1073 case R_ARM_RBASE:
1074 break;
1075
1076 case R_ARM_RABS32:
1077 CoffAddFixup (Rel->r_offset, EFI_IMAGE_REL_BASED_HIGHLOW);
1078 break;
1079
1080 default:
1081 Error (NULL, 0, 3000, "Invalid", "%s bad ARM dynamic relocations, unknown type %d.", mInImageName, ELF32_R_TYPE (Rel->r_info));
1082 break;
1083 }
1084 }
1085 break;
1086 }
1087 }
1088 }
1089
1090 //
1091 // Pad by adding empty entries.
1092 //
1093 while (mCoffOffset & (mCoffAlignment - 1)) {
1094 CoffAddFixupEntry(0);
1095 }
1096
1097 NtHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)(mCoffFile + mNtHdrOffset);
1098 Dir = &NtHdr->Pe32.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC];
1099 Dir->Size = mCoffOffset - mRelocOffset;
1100 if (Dir->Size == 0) {
1101 // If no relocations, null out the directory entry and don't add the .reloc section
1102 Dir->VirtualAddress = 0;
1103 NtHdr->Pe32.FileHeader.NumberOfSections--;
1104 } else {
1105 Dir->VirtualAddress = mRelocOffset;
1106 CreateSectionHeader (".reloc", mRelocOffset, mCoffOffset - mRelocOffset,
1107 EFI_IMAGE_SCN_CNT_INITIALIZED_DATA
1108 | EFI_IMAGE_SCN_MEM_DISCARDABLE
1109 | EFI_IMAGE_SCN_MEM_READ);
1110 }
1111
1112 }
1113
1114 STATIC
1115 VOID
1116 WriteDebug32 (
1117 VOID
1118 )
1119 {
1120 UINT32 Len;
1121 EFI_IMAGE_OPTIONAL_HEADER_UNION *NtHdr;
1122 EFI_IMAGE_DATA_DIRECTORY *DataDir;
1123 EFI_IMAGE_DEBUG_DIRECTORY_ENTRY *Dir;
1124 EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY *Nb10;
1125
1126 Len = strlen(mInImageName) + 1;
1127
1128 Dir = (EFI_IMAGE_DEBUG_DIRECTORY_ENTRY*)(mCoffFile + mDebugOffset);
1129 Dir->Type = EFI_IMAGE_DEBUG_TYPE_CODEVIEW;
1130 Dir->SizeOfData = sizeof(EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY) + Len;
1131 Dir->RVA = mDebugOffset + sizeof(EFI_IMAGE_DEBUG_DIRECTORY_ENTRY);
1132 Dir->FileOffset = mDebugOffset + sizeof(EFI_IMAGE_DEBUG_DIRECTORY_ENTRY);
1133
1134 Nb10 = (EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY*)(Dir + 1);
1135 Nb10->Signature = CODEVIEW_SIGNATURE_NB10;
1136 strcpy ((char *)(Nb10 + 1), mInImageName);
1137
1138
1139 NtHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)(mCoffFile + mNtHdrOffset);
1140 DataDir = &NtHdr->Pe32.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG];
1141 DataDir->VirtualAddress = mDebugOffset;
1142 DataDir->Size = sizeof(EFI_IMAGE_DEBUG_DIRECTORY_ENTRY);
1143 }
1144
1145 STATIC
1146 VOID
1147 SetImageSize32 (
1148 VOID
1149 )
1150 {
1151 EFI_IMAGE_OPTIONAL_HEADER_UNION *NtHdr;
1152
1153 //
1154 // Set image size
1155 //
1156 NtHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)(mCoffFile + mNtHdrOffset);
1157 NtHdr->Pe32.OptionalHeader.SizeOfImage = mCoffOffset;
1158 }
1159
1160 STATIC
1161 VOID
1162 CleanUp32 (
1163 VOID
1164 )
1165 {
1166 if (mCoffSectionsOffset != NULL) {
1167 free (mCoffSectionsOffset);
1168 }
1169 }
1170
1171