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