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