]> git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Source/C/GenFw/Elf32Convert.c
BaseTools: Replace BSD License with BSD+Patent License
[mirror_edk2.git] / BaseTools / Source / C / GenFw / Elf32Convert.c
1 /** @file
2 Elf32 Convert solution
3
4 Copyright (c) 2010 - 2018, Intel Corporation. All rights reserved.<BR>
5 Portions copyright (c) 2013, ARM Ltd. All rights reserved.<BR>
6
7 SPDX-License-Identifier: BSD-2-Clause-Patent
8
9 **/
10
11 #include "WinNtInclude.h"
12
13 #ifndef __GNUC__
14 #include <windows.h>
15 #include <io.h>
16 #endif
17 #include <assert.h>
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <time.h>
22 #include <ctype.h>
23
24 #include <Common/UefiBaseTypes.h>
25 #include <IndustryStandard/PeImage.h>
26
27 #include "PeCoffLib.h"
28 #include "EfiUtilityMsgs.h"
29
30 #include "GenFw.h"
31 #include "ElfConvert.h"
32 #include "Elf32Convert.h"
33
34 STATIC
35 VOID
36 ScanSections32 (
37 VOID
38 );
39
40 STATIC
41 BOOLEAN
42 WriteSections32 (
43 SECTION_FILTER_TYPES FilterType
44 );
45
46 STATIC
47 VOID
48 WriteRelocations32 (
49 VOID
50 );
51
52 STATIC
53 VOID
54 WriteDebug32 (
55 VOID
56 );
57
58 STATIC
59 VOID
60 SetImageSize32 (
61 VOID
62 );
63
64 STATIC
65 VOID
66 CleanUp32 (
67 VOID
68 );
69
70 //
71 // Rename ELF32 structures to common names to help when porting to ELF64.
72 //
73 typedef Elf32_Shdr Elf_Shdr;
74 typedef Elf32_Ehdr Elf_Ehdr;
75 typedef Elf32_Rel Elf_Rel;
76 typedef Elf32_Sym Elf_Sym;
77 typedef Elf32_Phdr Elf_Phdr;
78 typedef Elf32_Dyn Elf_Dyn;
79 #define ELFCLASS ELFCLASS32
80 #define ELF_R_TYPE(r) ELF32_R_TYPE(r)
81 #define ELF_R_SYM(r) ELF32_R_SYM(r)
82
83 //
84 // Well known ELF structures.
85 //
86 STATIC Elf_Ehdr *mEhdr;
87 STATIC Elf_Shdr *mShdrBase;
88 STATIC Elf_Phdr *mPhdrBase;
89
90 //
91 // Coff information
92 //
93 STATIC UINT32 mCoffAlignment = 0x20;
94
95 //
96 // PE section alignment.
97 //
98 STATIC const UINT16 mCoffNbrSections = 4;
99
100 //
101 // ELF sections to offset in Coff file.
102 //
103 STATIC UINT32 *mCoffSectionsOffset = NULL;
104
105 //
106 // Offsets in COFF file
107 //
108 STATIC UINT32 mNtHdrOffset;
109 STATIC UINT32 mTextOffset;
110 STATIC UINT32 mDataOffset;
111 STATIC UINT32 mHiiRsrcOffset;
112 STATIC UINT32 mRelocOffset;
113 STATIC UINT32 mDebugOffset;
114
115 //
116 // Initialization Function
117 //
118 BOOLEAN
119 InitializeElf32 (
120 UINT8 *FileBuffer,
121 ELF_FUNCTION_TABLE *ElfFunctions
122 )
123 {
124 //
125 // Initialize data pointer and structures.
126 //
127 mEhdr = (Elf_Ehdr*) FileBuffer;
128
129 //
130 // Check the ELF32 specific header information.
131 //
132 if (mEhdr->e_ident[EI_CLASS] != ELFCLASS32) {
133 Error (NULL, 0, 3000, "Unsupported", "ELF EI_DATA not ELFCLASS32");
134 return FALSE;
135 }
136 if (mEhdr->e_ident[EI_DATA] != ELFDATA2LSB) {
137 Error (NULL, 0, 3000, "Unsupported", "ELF EI_DATA not ELFDATA2LSB");
138 return FALSE;
139 }
140 if ((mEhdr->e_type != ET_EXEC) && (mEhdr->e_type != ET_DYN)) {
141 Error (NULL, 0, 3000, "Unsupported", "ELF e_type not ET_EXEC or ET_DYN");
142 return FALSE;
143 }
144 if (!((mEhdr->e_machine == EM_386) || (mEhdr->e_machine == EM_ARM))) {
145 Error (NULL, 0, 3000, "Unsupported", "ELF e_machine not EM_386 or EM_ARM");
146 return FALSE;
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_WRITE | SHF_ALLOC)) == 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_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
753 Error (NULL, 0, 3000, "Invalid",
754 "%s: Bad definition for symbol '%s'@%#x or unsupported symbol type. "
755 "For example, absolute and undefined symbols are not supported.",
756 mInImageName, SymName, Sym->st_value);
757
758 exit(EXIT_FAILURE);
759 }
760 SymShdr = GetShdrByIndex(Sym->st_shndx);
761
762 //
763 // Convert the relocation data to a pointer into the coff file.
764 //
765 // Note:
766 // r_offset is the virtual address of the storage unit to be relocated.
767 // sh_addr is the virtual address for the base of the section.
768 //
769 Targ = mCoffFile + SecOffset + (Rel->r_offset - SecShdr->sh_addr);
770
771 //
772 // Determine how to handle each relocation type based on the machine type.
773 //
774 if (mEhdr->e_machine == EM_386) {
775 switch (ELF_R_TYPE(Rel->r_info)) {
776 case R_386_NONE:
777 break;
778 case R_386_32:
779 //
780 // Absolute relocation.
781 // Converts Targ from a absolute virtual address to the absolute
782 // COFF address.
783 //
784 *(UINT32 *)Targ = *(UINT32 *)Targ - SymShdr->sh_addr
785 + mCoffSectionsOffset[Sym->st_shndx];
786 break;
787 case R_386_PC32:
788 //
789 // Relative relocation: Symbol - Ip + Addend
790 //
791 *(UINT32 *)Targ = *(UINT32 *)Targ
792 + (mCoffSectionsOffset[Sym->st_shndx] - SymShdr->sh_addr)
793 - (SecOffset - SecShdr->sh_addr);
794 break;
795 default:
796 Error (NULL, 0, 3000, "Invalid", "%s unsupported ELF EM_386 relocation 0x%x.", mInImageName, (unsigned) ELF_R_TYPE(Rel->r_info));
797 }
798 } else if (mEhdr->e_machine == EM_ARM) {
799 switch (ELF32_R_TYPE(Rel->r_info)) {
800 case R_ARM_RBASE:
801 // No relocation - no action required
802 // break skipped
803
804 case R_ARM_PC24:
805 case R_ARM_REL32:
806 case R_ARM_XPC25:
807 case R_ARM_THM_PC22:
808 case R_ARM_THM_JUMP19:
809 case R_ARM_CALL:
810 case R_ARM_JMP24:
811 case R_ARM_THM_JUMP24:
812 case R_ARM_PREL31:
813 case R_ARM_MOVW_PREL_NC:
814 case R_ARM_MOVT_PREL:
815 case R_ARM_THM_MOVW_PREL_NC:
816 case R_ARM_THM_MOVT_PREL:
817 case R_ARM_THM_JMP6:
818 case R_ARM_THM_ALU_PREL_11_0:
819 case R_ARM_THM_PC12:
820 case R_ARM_REL32_NOI:
821 case R_ARM_ALU_PC_G0_NC:
822 case R_ARM_ALU_PC_G0:
823 case R_ARM_ALU_PC_G1_NC:
824 case R_ARM_ALU_PC_G1:
825 case R_ARM_ALU_PC_G2:
826 case R_ARM_LDR_PC_G1:
827 case R_ARM_LDR_PC_G2:
828 case R_ARM_LDRS_PC_G0:
829 case R_ARM_LDRS_PC_G1:
830 case R_ARM_LDRS_PC_G2:
831 case R_ARM_LDC_PC_G0:
832 case R_ARM_LDC_PC_G1:
833 case R_ARM_LDC_PC_G2:
834 case R_ARM_THM_JUMP11:
835 case R_ARM_THM_JUMP8:
836 case R_ARM_TLS_GD32:
837 case R_ARM_TLS_LDM32:
838 case R_ARM_TLS_IE32:
839 // Thease are all PC-relative relocations and don't require modification
840 // GCC does not seem to have the concept of a application that just needs to get relocated.
841 break;
842
843 case R_ARM_THM_MOVW_ABS_NC:
844 // MOVW is only lower 16-bits of the addres
845 Address = (UINT16)(Sym->st_value - SymShdr->sh_addr + mCoffSectionsOffset[Sym->st_shndx]);
846 ThumbMovtImmediatePatch ((UINT16 *)Targ, Address);
847 break;
848
849 case R_ARM_THM_MOVT_ABS:
850 // MOVT is only upper 16-bits of the addres
851 Address = (UINT16)((Sym->st_value - SymShdr->sh_addr + mCoffSectionsOffset[Sym->st_shndx]) >> 16);
852 ThumbMovtImmediatePatch ((UINT16 *)Targ, Address);
853 break;
854
855 case R_ARM_ABS32:
856 case R_ARM_RABS32:
857 //
858 // Absolute relocation.
859 //
860 *(UINT32 *)Targ = *(UINT32 *)Targ - SymShdr->sh_addr + mCoffSectionsOffset[Sym->st_shndx];
861 break;
862
863 default:
864 Error (NULL, 0, 3000, "Invalid", "WriteSections (): %s unsupported ELF EM_ARM relocation 0x%x.", mInImageName, (unsigned) ELF32_R_TYPE(Rel->r_info));
865 }
866 }
867 }
868 }
869 }
870
871 return TRUE;
872 }
873
874 UINTN gMovwOffset = 0;
875
876 STATIC
877 VOID
878 WriteRelocations32 (
879 VOID
880 )
881 {
882 UINT32 Index;
883 EFI_IMAGE_OPTIONAL_HEADER_UNION *NtHdr;
884 EFI_IMAGE_DATA_DIRECTORY *Dir;
885 BOOLEAN FoundRelocations;
886 Elf_Dyn *Dyn;
887 Elf_Rel *Rel;
888 UINTN RelElementSize;
889 UINTN RelSize;
890 UINTN RelOffset;
891 UINTN K;
892 Elf32_Phdr *DynamicSegment;
893
894 for (Index = 0, FoundRelocations = FALSE; Index < mEhdr->e_shnum; Index++) {
895 Elf_Shdr *RelShdr = GetShdrByIndex(Index);
896 if ((RelShdr->sh_type == SHT_REL) || (RelShdr->sh_type == SHT_RELA)) {
897 Elf_Shdr *SecShdr = GetShdrByIndex (RelShdr->sh_info);
898 if (IsTextShdr(SecShdr) || IsDataShdr(SecShdr)) {
899 UINT32 RelIdx;
900
901 FoundRelocations = TRUE;
902 for (RelIdx = 0; RelIdx < RelShdr->sh_size; RelIdx += RelShdr->sh_entsize) {
903 Rel = (Elf_Rel *)((UINT8*)mEhdr + RelShdr->sh_offset + RelIdx);
904
905 if (mEhdr->e_machine == EM_386) {
906 switch (ELF_R_TYPE(Rel->r_info)) {
907 case R_386_NONE:
908 case R_386_PC32:
909 //
910 // No fixup entry required.
911 //
912 break;
913 case R_386_32:
914 //
915 // Creates a relative relocation entry from the absolute entry.
916 //
917 CoffAddFixup(mCoffSectionsOffset[RelShdr->sh_info]
918 + (Rel->r_offset - SecShdr->sh_addr),
919 EFI_IMAGE_REL_BASED_HIGHLOW);
920 break;
921 default:
922 Error (NULL, 0, 3000, "Invalid", "%s unsupported ELF EM_386 relocation 0x%x.", mInImageName, (unsigned) ELF_R_TYPE(Rel->r_info));
923 }
924 } else if (mEhdr->e_machine == EM_ARM) {
925 switch (ELF32_R_TYPE(Rel->r_info)) {
926 case R_ARM_RBASE:
927 // No relocation - no action required
928 // break skipped
929
930 case R_ARM_PC24:
931 case R_ARM_REL32:
932 case R_ARM_XPC25:
933 case R_ARM_THM_PC22:
934 case R_ARM_THM_JUMP19:
935 case R_ARM_CALL:
936 case R_ARM_JMP24:
937 case R_ARM_THM_JUMP24:
938 case R_ARM_PREL31:
939 case R_ARM_MOVW_PREL_NC:
940 case R_ARM_MOVT_PREL:
941 case R_ARM_THM_MOVW_PREL_NC:
942 case R_ARM_THM_MOVT_PREL:
943 case R_ARM_THM_JMP6:
944 case R_ARM_THM_ALU_PREL_11_0:
945 case R_ARM_THM_PC12:
946 case R_ARM_REL32_NOI:
947 case R_ARM_ALU_PC_G0_NC:
948 case R_ARM_ALU_PC_G0:
949 case R_ARM_ALU_PC_G1_NC:
950 case R_ARM_ALU_PC_G1:
951 case R_ARM_ALU_PC_G2:
952 case R_ARM_LDR_PC_G1:
953 case R_ARM_LDR_PC_G2:
954 case R_ARM_LDRS_PC_G0:
955 case R_ARM_LDRS_PC_G1:
956 case R_ARM_LDRS_PC_G2:
957 case R_ARM_LDC_PC_G0:
958 case R_ARM_LDC_PC_G1:
959 case R_ARM_LDC_PC_G2:
960 case R_ARM_THM_JUMP11:
961 case R_ARM_THM_JUMP8:
962 case R_ARM_TLS_GD32:
963 case R_ARM_TLS_LDM32:
964 case R_ARM_TLS_IE32:
965 // Thease are all PC-relative relocations and don't require modification
966 break;
967
968 case R_ARM_THM_MOVW_ABS_NC:
969 CoffAddFixup (
970 mCoffSectionsOffset[RelShdr->sh_info]
971 + (Rel->r_offset - SecShdr->sh_addr),
972 EFI_IMAGE_REL_BASED_ARM_MOV32T
973 );
974
975 // PE/COFF treats MOVW/MOVT relocation as single 64-bit instruction
976 // Track this address so we can log an error for unsupported sequence of MOVW/MOVT
977 gMovwOffset = mCoffSectionsOffset[RelShdr->sh_info] + (Rel->r_offset - SecShdr->sh_addr);
978 break;
979
980 case R_ARM_THM_MOVT_ABS:
981 if ((gMovwOffset + 4) != (mCoffSectionsOffset[RelShdr->sh_info] + (Rel->r_offset - SecShdr->sh_addr))) {
982 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));
983 }
984 break;
985
986 case R_ARM_ABS32:
987 case R_ARM_RABS32:
988 CoffAddFixup (
989 mCoffSectionsOffset[RelShdr->sh_info]
990 + (Rel->r_offset - SecShdr->sh_addr),
991 EFI_IMAGE_REL_BASED_HIGHLOW
992 );
993 break;
994
995 default:
996 Error (NULL, 0, 3000, "Invalid", "WriteRelocations(): %s unsupported ELF EM_ARM relocation 0x%x.", mInImageName, (unsigned) ELF32_R_TYPE(Rel->r_info));
997 }
998 } else {
999 Error (NULL, 0, 3000, "Not Supported", "This tool does not support relocations for ELF with e_machine %u (processor type).", (unsigned) mEhdr->e_machine);
1000 }
1001 }
1002 }
1003 }
1004 }
1005
1006 if (!FoundRelocations && (mEhdr->e_machine == EM_ARM)) {
1007 /* Try again, but look for PT_DYNAMIC instead of SHT_REL */
1008
1009 for (Index = 0; Index < mEhdr->e_phnum; Index++) {
1010 RelElementSize = 0;
1011 RelSize = 0;
1012 RelOffset = 0;
1013
1014 DynamicSegment = GetPhdrByIndex (Index);
1015
1016 if (DynamicSegment->p_type == PT_DYNAMIC) {
1017 Dyn = (Elf32_Dyn *) ((UINT8 *)mEhdr + DynamicSegment->p_offset);
1018
1019 while (Dyn->d_tag != DT_NULL) {
1020 switch (Dyn->d_tag) {
1021 case DT_REL:
1022 RelOffset = Dyn->d_un.d_val;
1023 break;
1024
1025 case DT_RELSZ:
1026 RelSize = Dyn->d_un.d_val;
1027 break;
1028
1029 case DT_RELENT:
1030 RelElementSize = Dyn->d_un.d_val;
1031 break;
1032
1033 default:
1034 break;
1035 }
1036 Dyn++;
1037 }
1038 if (( RelOffset == 0 ) || ( RelSize == 0 ) || ( RelElementSize == 0 )) {
1039 Error (NULL, 0, 3000, "Invalid", "%s bad ARM dynamic relocations.", mInImageName);
1040 }
1041
1042 for (Index = 0; Index < mEhdr->e_shnum; Index++) {
1043 Elf_Shdr *shdr = GetShdrByIndex(Index);
1044
1045 //
1046 // The PT_DYNAMIC section contains DT_REL relocations whose r_offset
1047 // field is relative to the base of a segment (or the entire image),
1048 // and not to the base of an ELF input section as is the case for
1049 // SHT_REL sections. This means that we cannot fix up such relocations
1050 // unless we cross-reference ELF sections and segments, considering
1051 // that the output placement recorded in mCoffSectionsOffset[] is
1052 // section based, not segment based.
1053 //
1054 // Fortunately, there is a simple way around this: we require that the
1055 // in-memory layout of the ELF and PE/COFF versions of the binary is
1056 // identical. That way, r_offset will retain its validity as a PE/COFF
1057 // image offset, and we can record it in the COFF fixup table
1058 // unmodified.
1059 //
1060 if (shdr->sh_addr != mCoffSectionsOffset[Index]) {
1061 Error (NULL, 0, 3000,
1062 "Invalid", "%s: PT_DYNAMIC relocations require identical ELF and PE/COFF section offsets.",
1063 mInImageName);
1064 }
1065 }
1066
1067 for (K = 0; K < RelSize; K += RelElementSize) {
1068
1069 if (DynamicSegment->p_paddr == 0) {
1070 // Older versions of the ARM ELF (SWS ESPC 0003 B-02) specification define DT_REL
1071 // as an offset in the dynamic segment. p_paddr is defined to be zero for ARM tools
1072 Rel = (Elf32_Rel *) ((UINT8 *) mEhdr + DynamicSegment->p_offset + RelOffset + K);
1073 } else {
1074 // This is how it reads in the generic ELF specification
1075 Rel = (Elf32_Rel *) ((UINT8 *) mEhdr + RelOffset + K);
1076 }
1077
1078 switch (ELF32_R_TYPE (Rel->r_info)) {
1079 case R_ARM_RBASE:
1080 break;
1081
1082 case R_ARM_RABS32:
1083 CoffAddFixup (Rel->r_offset, EFI_IMAGE_REL_BASED_HIGHLOW);
1084 break;
1085
1086 default:
1087 Error (NULL, 0, 3000, "Invalid", "%s bad ARM dynamic relocations, unknown type %d.", mInImageName, ELF32_R_TYPE (Rel->r_info));
1088 break;
1089 }
1090 }
1091 break;
1092 }
1093 }
1094 }
1095
1096 //
1097 // Pad by adding empty entries.
1098 //
1099 while (mCoffOffset & (mCoffAlignment - 1)) {
1100 CoffAddFixupEntry(0);
1101 }
1102
1103 NtHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)(mCoffFile + mNtHdrOffset);
1104 Dir = &NtHdr->Pe32.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC];
1105 Dir->Size = mCoffOffset - mRelocOffset;
1106 if (Dir->Size == 0) {
1107 // If no relocations, null out the directory entry and don't add the .reloc section
1108 Dir->VirtualAddress = 0;
1109 NtHdr->Pe32.FileHeader.NumberOfSections--;
1110 } else {
1111 Dir->VirtualAddress = mRelocOffset;
1112 CreateSectionHeader (".reloc", mRelocOffset, mCoffOffset - mRelocOffset,
1113 EFI_IMAGE_SCN_CNT_INITIALIZED_DATA
1114 | EFI_IMAGE_SCN_MEM_DISCARDABLE
1115 | EFI_IMAGE_SCN_MEM_READ);
1116 }
1117
1118 }
1119
1120 STATIC
1121 VOID
1122 WriteDebug32 (
1123 VOID
1124 )
1125 {
1126 UINT32 Len;
1127 EFI_IMAGE_OPTIONAL_HEADER_UNION *NtHdr;
1128 EFI_IMAGE_DATA_DIRECTORY *DataDir;
1129 EFI_IMAGE_DEBUG_DIRECTORY_ENTRY *Dir;
1130 EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY *Nb10;
1131
1132 Len = strlen(mInImageName) + 1;
1133
1134 Dir = (EFI_IMAGE_DEBUG_DIRECTORY_ENTRY*)(mCoffFile + mDebugOffset);
1135 Dir->Type = EFI_IMAGE_DEBUG_TYPE_CODEVIEW;
1136 Dir->SizeOfData = sizeof(EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY) + Len;
1137 Dir->RVA = mDebugOffset + sizeof(EFI_IMAGE_DEBUG_DIRECTORY_ENTRY);
1138 Dir->FileOffset = mDebugOffset + sizeof(EFI_IMAGE_DEBUG_DIRECTORY_ENTRY);
1139
1140 Nb10 = (EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY*)(Dir + 1);
1141 Nb10->Signature = CODEVIEW_SIGNATURE_NB10;
1142 strcpy ((char *)(Nb10 + 1), mInImageName);
1143
1144
1145 NtHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)(mCoffFile + mNtHdrOffset);
1146 DataDir = &NtHdr->Pe32.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG];
1147 DataDir->VirtualAddress = mDebugOffset;
1148 DataDir->Size = sizeof(EFI_IMAGE_DEBUG_DIRECTORY_ENTRY);
1149 }
1150
1151 STATIC
1152 VOID
1153 SetImageSize32 (
1154 VOID
1155 )
1156 {
1157 EFI_IMAGE_OPTIONAL_HEADER_UNION *NtHdr;
1158
1159 //
1160 // Set image size
1161 //
1162 NtHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)(mCoffFile + mNtHdrOffset);
1163 NtHdr->Pe32.OptionalHeader.SizeOfImage = mCoffOffset;
1164 }
1165
1166 STATIC
1167 VOID
1168 CleanUp32 (
1169 VOID
1170 )
1171 {
1172 if (mCoffSectionsOffset != NULL) {
1173 free (mCoffSectionsOffset);
1174 }
1175 }
1176
1177