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