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