[infiniband] Use "%d" as format specifier for LIDs
[ipxe.git] / src / util / elf2efi.c
1 /*
2 * Copyright (C) 2009 Michael Brown <mbrown@fensystems.co.uk>.
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License as
6 * published by the Free Software Foundation; either version 2 of the
7 * License, or any later version.
8 *
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17 * 02110-1301, USA.
18 */
19
20 #define _GNU_SOURCE
21 #define PACKAGE "elf2efi"
22 #define PACKAGE_VERSION "1"
23 #define FILE_LICENCE(...) extern void __file_licence ( void )
24 #include <stdint.h>
25 #include <stddef.h>
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <unistd.h>
30 #include <errno.h>
31 #include <assert.h>
32 #include <getopt.h>
33 #include <bfd.h>
34 #include <ipxe/efi/Uefi.h>
35 #include <ipxe/efi/IndustryStandard/PeImage.h>
36 #include <libgen.h>
37
38 #define eprintf(...) fprintf ( stderr, __VA_ARGS__ )
39
40 #define EFI_FILE_ALIGN 0x20
41
42 struct pe_section {
43 struct pe_section *next;
44 EFI_IMAGE_SECTION_HEADER hdr;
45 void ( * fixup ) ( struct pe_section *section );
46 uint8_t contents[0];
47 };
48
49 struct pe_relocs {
50 struct pe_relocs *next;
51 unsigned long start_rva;
52 unsigned int used_relocs;
53 unsigned int total_relocs;
54 uint16_t *relocs;
55 };
56
57 struct pe_header {
58 EFI_IMAGE_DOS_HEADER dos;
59 uint8_t padding[128];
60 #if defined(EFI_TARGET_IA32)
61 EFI_IMAGE_NT_HEADERS32 nt;
62 #elif defined(EFI_TARGET_X64)
63 EFI_IMAGE_NT_HEADERS64 nt;
64 #endif
65 };
66
67 static struct pe_header efi_pe_header = {
68 .dos = {
69 .e_magic = EFI_IMAGE_DOS_SIGNATURE,
70 .e_lfanew = offsetof ( typeof ( efi_pe_header ), nt ),
71 },
72 .nt = {
73 .Signature = EFI_IMAGE_NT_SIGNATURE,
74 .FileHeader = {
75 #if defined(EFI_TARGET_IA32)
76 .Machine = EFI_IMAGE_MACHINE_IA32,
77 #elif defined(EFI_TARGET_X64)
78 .Machine = EFI_IMAGE_MACHINE_X64,
79 #endif
80 .TimeDateStamp = 0x10d1a884,
81 .SizeOfOptionalHeader =
82 sizeof ( efi_pe_header.nt.OptionalHeader ),
83 .Characteristics = ( EFI_IMAGE_FILE_DLL |
84 #if defined(EFI_TARGET_IA32)
85 EFI_IMAGE_FILE_32BIT_MACHINE |
86 #endif
87 EFI_IMAGE_FILE_EXECUTABLE_IMAGE ),
88 },
89 .OptionalHeader = {
90 #if defined(EFI_TARGET_IA32)
91 .Magic = EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC,
92 #elif defined(EFI_TARGET_X64)
93 .Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC,
94 #endif
95 .MajorLinkerVersion = 42,
96 .MinorLinkerVersion = 42,
97 .SectionAlignment = EFI_FILE_ALIGN,
98 .FileAlignment = EFI_FILE_ALIGN,
99 .SizeOfImage = sizeof ( efi_pe_header ),
100 .SizeOfHeaders = sizeof ( efi_pe_header ),
101 .NumberOfRvaAndSizes =
102 EFI_IMAGE_NUMBER_OF_DIRECTORY_ENTRIES,
103 },
104 },
105 };
106
107 /** Command-line options */
108 struct options {
109 unsigned int subsystem;
110 };
111
112 /**
113 * Allocate memory
114 *
115 * @v len Length of memory to allocate
116 * @ret ptr Pointer to allocated memory
117 */
118 static void * xmalloc ( size_t len ) {
119 void *ptr;
120
121 ptr = malloc ( len );
122 if ( ! ptr ) {
123 eprintf ( "Could not allocate %zd bytes\n", len );
124 exit ( 1 );
125 }
126
127 return ptr;
128 }
129
130 /**
131 * Align section within PE file
132 *
133 * @v offset Unaligned offset
134 * @ret aligned_offset Aligned offset
135 */
136 static unsigned long efi_file_align ( unsigned long offset ) {
137 return ( ( offset + EFI_FILE_ALIGN - 1 ) & ~( EFI_FILE_ALIGN - 1 ) );
138 }
139
140 /**
141 * Generate entry in PE relocation table
142 *
143 * @v pe_reltab PE relocation table
144 * @v rva RVA
145 * @v size Size of relocation entry
146 */
147 static void generate_pe_reloc ( struct pe_relocs **pe_reltab,
148 unsigned long rva, size_t size ) {
149 unsigned long start_rva;
150 uint16_t reloc;
151 struct pe_relocs *pe_rel;
152 uint16_t *relocs;
153
154 /* Construct */
155 start_rva = ( rva & ~0xfff );
156 reloc = ( rva & 0xfff );
157 switch ( size ) {
158 case 8:
159 reloc |= 0xa000;
160 break;
161 case 4:
162 reloc |= 0x3000;
163 break;
164 case 2:
165 reloc |= 0x2000;
166 break;
167 default:
168 eprintf ( "Unsupported relocation size %zd\n", size );
169 exit ( 1 );
170 }
171
172 /* Locate or create PE relocation table */
173 for ( pe_rel = *pe_reltab ; pe_rel ; pe_rel = pe_rel->next ) {
174 if ( pe_rel->start_rva == start_rva )
175 break;
176 }
177 if ( ! pe_rel ) {
178 pe_rel = xmalloc ( sizeof ( *pe_rel ) );
179 memset ( pe_rel, 0, sizeof ( *pe_rel ) );
180 pe_rel->next = *pe_reltab;
181 *pe_reltab = pe_rel;
182 pe_rel->start_rva = start_rva;
183 }
184
185 /* Expand relocation list if necessary */
186 if ( pe_rel->used_relocs < pe_rel->total_relocs ) {
187 relocs = pe_rel->relocs;
188 } else {
189 pe_rel->total_relocs = ( pe_rel->total_relocs ?
190 ( pe_rel->total_relocs * 2 ) : 256 );
191 relocs = xmalloc ( pe_rel->total_relocs *
192 sizeof ( pe_rel->relocs[0] ) );
193 memset ( relocs, 0,
194 pe_rel->total_relocs * sizeof ( pe_rel->relocs[0] ) );
195 memcpy ( relocs, pe_rel->relocs,
196 pe_rel->used_relocs * sizeof ( pe_rel->relocs[0] ) );
197 free ( pe_rel->relocs );
198 pe_rel->relocs = relocs;
199 }
200
201 /* Store relocation */
202 pe_rel->relocs[ pe_rel->used_relocs++ ] = reloc;
203 }
204
205 /**
206 * Calculate size of binary PE relocation table
207 *
208 * @v pe_reltab PE relocation table
209 * @v buffer Buffer to contain binary table, or NULL
210 * @ret size Size of binary table
211 */
212 static size_t output_pe_reltab ( struct pe_relocs *pe_reltab,
213 void *buffer ) {
214 struct pe_relocs *pe_rel;
215 unsigned int num_relocs;
216 size_t size;
217 size_t total_size = 0;
218
219 for ( pe_rel = pe_reltab ; pe_rel ; pe_rel = pe_rel->next ) {
220 num_relocs = ( ( pe_rel->used_relocs + 1 ) & ~1 );
221 size = ( sizeof ( uint32_t ) /* VirtualAddress */ +
222 sizeof ( uint32_t ) /* SizeOfBlock */ +
223 ( num_relocs * sizeof ( uint16_t ) ) );
224 if ( buffer ) {
225 *( (uint32_t *) ( buffer + total_size + 0 ) )
226 = pe_rel->start_rva;
227 *( (uint32_t *) ( buffer + total_size + 4 ) ) = size;
228 memcpy ( ( buffer + total_size + 8 ), pe_rel->relocs,
229 ( num_relocs * sizeof ( uint16_t ) ) );
230 }
231 total_size += size;
232 }
233
234 return total_size;
235 }
236
237 /**
238 * Open input BFD file
239 *
240 * @v filename File name
241 * @ret ibfd BFD file
242 */
243 static bfd * open_input_bfd ( const char *filename ) {
244 bfd *bfd;
245
246 /* Open the file */
247 bfd = bfd_openr ( filename, NULL );
248 if ( ! bfd ) {
249 eprintf ( "Cannot open %s: ", filename );
250 bfd_perror ( NULL );
251 exit ( 1 );
252 }
253
254 /* The call to bfd_check_format() must be present, otherwise
255 * we get a segfault from later BFD calls.
256 */
257 if ( ! bfd_check_format ( bfd, bfd_object ) ) {
258 eprintf ( "%s is not an object file: ", filename );
259 bfd_perror ( NULL );
260 exit ( 1 );
261 }
262
263 return bfd;
264 }
265
266 /**
267 * Read symbol table
268 *
269 * @v bfd BFD file
270 */
271 static asymbol ** read_symtab ( bfd *bfd ) {
272 long symtab_size;
273 asymbol **symtab;
274 long symcount;
275
276 /* Get symbol table size */
277 symtab_size = bfd_get_symtab_upper_bound ( bfd );
278 if ( symtab_size < 0 ) {
279 bfd_perror ( "Could not get symbol table upper bound" );
280 exit ( 1 );
281 }
282
283 /* Allocate and read symbol table */
284 symtab = xmalloc ( symtab_size );
285 symcount = bfd_canonicalize_symtab ( bfd, symtab );
286 if ( symcount < 0 ) {
287 bfd_perror ( "Cannot read symbol table" );
288 exit ( 1 );
289 }
290
291 return symtab;
292 }
293
294 /**
295 * Read relocation table
296 *
297 * @v bfd BFD file
298 * @v symtab Symbol table
299 * @v section Section
300 * @v symtab Symbol table
301 * @ret reltab Relocation table
302 */
303 static arelent ** read_reltab ( bfd *bfd, asymbol **symtab,
304 asection *section ) {
305 long reltab_size;
306 arelent **reltab;
307 long numrels;
308
309 /* Get relocation table size */
310 reltab_size = bfd_get_reloc_upper_bound ( bfd, section );
311 if ( reltab_size < 0 ) {
312 bfd_perror ( "Could not get relocation table upper bound" );
313 exit ( 1 );
314 }
315
316 /* Allocate and read relocation table */
317 reltab = xmalloc ( reltab_size );
318 numrels = bfd_canonicalize_reloc ( bfd, section, reltab, symtab );
319 if ( numrels < 0 ) {
320 bfd_perror ( "Cannot read relocation table" );
321 exit ( 1 );
322 }
323
324 return reltab;
325 }
326
327 /**
328 * Process section
329 *
330 * @v bfd BFD file
331 * @v pe_header PE file header
332 * @v section Section
333 * @ret new New PE section
334 */
335 static struct pe_section * process_section ( bfd *bfd,
336 struct pe_header *pe_header,
337 asection *section ) {
338 struct pe_section *new;
339 size_t section_memsz;
340 size_t section_filesz;
341 unsigned long flags = bfd_get_section_flags ( bfd, section );
342 unsigned long code_start;
343 unsigned long code_end;
344 unsigned long data_start;
345 unsigned long data_mid;
346 unsigned long data_end;
347 unsigned long start;
348 unsigned long end;
349 unsigned long *applicable_start;
350 unsigned long *applicable_end;
351
352 /* Extract current RVA limits from file header */
353 code_start = pe_header->nt.OptionalHeader.BaseOfCode;
354 code_end = ( code_start + pe_header->nt.OptionalHeader.SizeOfCode );
355 #if defined(EFI_TARGET_IA32)
356 data_start = pe_header->nt.OptionalHeader.BaseOfData;
357 #elif defined(EFI_TARGET_X64)
358 data_start = code_end;
359 #endif
360 data_mid = ( data_start +
361 pe_header->nt.OptionalHeader.SizeOfInitializedData );
362 data_end = ( data_mid +
363 pe_header->nt.OptionalHeader.SizeOfUninitializedData );
364
365 /* Allocate PE section */
366 section_memsz = bfd_section_size ( bfd, section );
367 section_filesz = ( ( flags & SEC_LOAD ) ?
368 efi_file_align ( section_memsz ) : 0 );
369 new = xmalloc ( sizeof ( *new ) + section_filesz );
370 memset ( new, 0, sizeof ( *new ) + section_filesz );
371
372 /* Fill in section header details */
373 strncpy ( ( char * ) new->hdr.Name, section->name,
374 sizeof ( new->hdr.Name ) );
375 new->hdr.Misc.VirtualSize = section_memsz;
376 new->hdr.VirtualAddress = bfd_get_section_vma ( bfd, section );
377 new->hdr.SizeOfRawData = section_filesz;
378
379 /* Fill in section characteristics and update RVA limits */
380 if ( flags & SEC_CODE ) {
381 /* .text-type section */
382 new->hdr.Characteristics =
383 ( EFI_IMAGE_SCN_CNT_CODE |
384 EFI_IMAGE_SCN_MEM_NOT_PAGED |
385 EFI_IMAGE_SCN_MEM_EXECUTE |
386 EFI_IMAGE_SCN_MEM_READ );
387 applicable_start = &code_start;
388 applicable_end = &code_end;
389 } else if ( flags & SEC_DATA ) {
390 /* .data-type section */
391 new->hdr.Characteristics =
392 ( EFI_IMAGE_SCN_CNT_INITIALIZED_DATA |
393 EFI_IMAGE_SCN_MEM_NOT_PAGED |
394 EFI_IMAGE_SCN_MEM_READ |
395 EFI_IMAGE_SCN_MEM_WRITE );
396 applicable_start = &data_start;
397 applicable_end = &data_mid;
398 } else if ( flags & SEC_READONLY ) {
399 /* .rodata-type section */
400 new->hdr.Characteristics =
401 ( EFI_IMAGE_SCN_CNT_INITIALIZED_DATA |
402 EFI_IMAGE_SCN_MEM_NOT_PAGED |
403 EFI_IMAGE_SCN_MEM_READ );
404 applicable_start = &data_start;
405 applicable_end = &data_mid;
406 } else if ( ! ( flags & SEC_LOAD ) ) {
407 /* .bss-type section */
408 new->hdr.Characteristics =
409 ( EFI_IMAGE_SCN_CNT_UNINITIALIZED_DATA |
410 EFI_IMAGE_SCN_MEM_NOT_PAGED |
411 EFI_IMAGE_SCN_MEM_READ |
412 EFI_IMAGE_SCN_MEM_WRITE );
413 applicable_start = &data_mid;
414 applicable_end = &data_end;
415 } else {
416 eprintf ( "Unrecognised characteristics %#lx for section %s\n",
417 flags, section->name );
418 exit ( 1 );
419 }
420
421 /* Copy in section contents */
422 if ( flags & SEC_LOAD ) {
423 if ( ! bfd_get_section_contents ( bfd, section, new->contents,
424 0, section_memsz ) ) {
425 eprintf ( "Cannot read section %s: ", section->name );
426 bfd_perror ( NULL );
427 exit ( 1 );
428 }
429 }
430
431 /* Update RVA limits */
432 start = new->hdr.VirtualAddress;
433 end = ( start + new->hdr.Misc.VirtualSize );
434 if ( ( ! *applicable_start ) || ( *applicable_start >= start ) )
435 *applicable_start = start;
436 if ( *applicable_end < end )
437 *applicable_end = end;
438 if ( data_start < code_end )
439 data_start = code_end;
440 if ( data_mid < data_start )
441 data_mid = data_start;
442 if ( data_end < data_mid )
443 data_end = data_mid;
444
445 /* Write RVA limits back to file header */
446 pe_header->nt.OptionalHeader.BaseOfCode = code_start;
447 pe_header->nt.OptionalHeader.SizeOfCode = ( code_end - code_start );
448 #if defined(EFI_TARGET_IA32)
449 pe_header->nt.OptionalHeader.BaseOfData = data_start;
450 #endif
451 pe_header->nt.OptionalHeader.SizeOfInitializedData =
452 ( data_mid - data_start );
453 pe_header->nt.OptionalHeader.SizeOfUninitializedData =
454 ( data_end - data_mid );
455
456 /* Update remaining file header fields */
457 pe_header->nt.FileHeader.NumberOfSections++;
458 pe_header->nt.OptionalHeader.SizeOfHeaders += sizeof ( new->hdr );
459 pe_header->nt.OptionalHeader.SizeOfImage =
460 efi_file_align ( data_end );
461
462 return new;
463 }
464
465 /**
466 * Process relocation record
467 *
468 * @v bfd BFD file
469 * @v section Section
470 * @v rel Relocation entry
471 * @v pe_reltab PE relocation table to fill in
472 */
473 static void process_reloc ( bfd *bfd __attribute__ (( unused )),
474 asection *section, arelent *rel,
475 struct pe_relocs **pe_reltab ) {
476 reloc_howto_type *howto = rel->howto;
477 asymbol *sym = *(rel->sym_ptr_ptr);
478 unsigned long offset = ( bfd_get_section_vma ( bfd, section ) +
479 rel->address );
480
481 if ( bfd_is_abs_section ( sym->section ) ) {
482 /* Skip absolute symbols; the symbol value won't
483 * change when the object is loaded.
484 */
485 } else if ( ( strcmp ( howto->name, "R_386_NONE" ) == 0 ) ||
486 ( strcmp ( howto->name, "R_X86_64_NONE" ) == 0 ) ) {
487 /* Ignore dummy relocations used by REQUIRE_SYMBOL() */
488 } else if ( strcmp ( howto->name, "R_X86_64_64" ) == 0 ) {
489 /* Generate an 8-byte PE relocation */
490 generate_pe_reloc ( pe_reltab, offset, 8 );
491 } else if ( strcmp ( howto->name, "R_386_32" ) == 0 ) {
492 /* Generate a 4-byte PE relocation */
493 generate_pe_reloc ( pe_reltab, offset, 4 );
494 } else if ( strcmp ( howto->name, "R_386_16" ) == 0 ) {
495 /* Generate a 2-byte PE relocation */
496 generate_pe_reloc ( pe_reltab, offset, 2 );
497 } else if ( ( strcmp ( howto->name, "R_386_PC32" ) == 0 ) ||
498 ( strcmp ( howto->name, "R_X86_64_PC32" ) == 0 ) ) {
499 /* Skip PC-relative relocations; all relative offsets
500 * remain unaltered when the object is loaded.
501 */
502 } else {
503 eprintf ( "Unrecognised relocation type %s\n", howto->name );
504 exit ( 1 );
505 }
506 }
507
508 /**
509 * Create relocations section
510 *
511 * @v pe_header PE file header
512 * @v pe_reltab PE relocation table
513 * @ret section Relocation section
514 */
515 static struct pe_section *
516 create_reloc_section ( struct pe_header *pe_header,
517 struct pe_relocs *pe_reltab ) {
518 struct pe_section *reloc;
519 size_t section_memsz;
520 size_t section_filesz;
521 EFI_IMAGE_DATA_DIRECTORY *relocdir;
522
523 /* Allocate PE section */
524 section_memsz = output_pe_reltab ( pe_reltab, NULL );
525 section_filesz = efi_file_align ( section_memsz );
526 reloc = xmalloc ( sizeof ( *reloc ) + section_filesz );
527 memset ( reloc, 0, sizeof ( *reloc ) + section_filesz );
528
529 /* Fill in section header details */
530 strncpy ( ( char * ) reloc->hdr.Name, ".reloc",
531 sizeof ( reloc->hdr.Name ) );
532 reloc->hdr.Misc.VirtualSize = section_memsz;
533 reloc->hdr.VirtualAddress = pe_header->nt.OptionalHeader.SizeOfImage;
534 reloc->hdr.SizeOfRawData = section_filesz;
535 reloc->hdr.Characteristics = ( EFI_IMAGE_SCN_CNT_INITIALIZED_DATA |
536 EFI_IMAGE_SCN_MEM_NOT_PAGED |
537 EFI_IMAGE_SCN_MEM_READ );
538
539 /* Copy in section contents */
540 output_pe_reltab ( pe_reltab, reloc->contents );
541
542 /* Update file header details */
543 pe_header->nt.FileHeader.NumberOfSections++;
544 pe_header->nt.OptionalHeader.SizeOfHeaders += sizeof ( reloc->hdr );
545 pe_header->nt.OptionalHeader.SizeOfImage += section_filesz;
546 relocdir = &(pe_header->nt.OptionalHeader.DataDirectory
547 [EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC]);
548 relocdir->VirtualAddress = reloc->hdr.VirtualAddress;
549 relocdir->Size = reloc->hdr.Misc.VirtualSize;
550
551 return reloc;
552 }
553
554 /**
555 * Fix up debug section
556 *
557 * @v debug Debug section
558 */
559 static void fixup_debug_section ( struct pe_section *debug ) {
560 EFI_IMAGE_DEBUG_DIRECTORY_ENTRY *contents;
561
562 /* Fix up FileOffset */
563 contents = ( ( void * ) debug->contents );
564 contents->FileOffset += ( debug->hdr.PointerToRawData -
565 debug->hdr.VirtualAddress );
566 }
567
568 /**
569 * Create debug section
570 *
571 * @v pe_header PE file header
572 * @ret section Debug section
573 */
574 static struct pe_section *
575 create_debug_section ( struct pe_header *pe_header, const char *filename ) {
576 struct pe_section *debug;
577 size_t section_memsz;
578 size_t section_filesz;
579 EFI_IMAGE_DATA_DIRECTORY *debugdir;
580 struct {
581 EFI_IMAGE_DEBUG_DIRECTORY_ENTRY debug;
582 EFI_IMAGE_DEBUG_CODEVIEW_RSDS_ENTRY rsds;
583 char name[ strlen ( filename ) + 1 ];
584 } *contents;
585
586 /* Allocate PE section */
587 section_memsz = sizeof ( *contents );
588 section_filesz = efi_file_align ( section_memsz );
589 debug = xmalloc ( sizeof ( *debug ) + section_filesz );
590 memset ( debug, 0, sizeof ( *debug ) + section_filesz );
591 contents = ( void * ) debug->contents;
592
593 /* Fill in section header details */
594 strncpy ( ( char * ) debug->hdr.Name, ".debug",
595 sizeof ( debug->hdr.Name ) );
596 debug->hdr.Misc.VirtualSize = section_memsz;
597 debug->hdr.VirtualAddress = pe_header->nt.OptionalHeader.SizeOfImage;
598 debug->hdr.SizeOfRawData = section_filesz;
599 debug->hdr.Characteristics = ( EFI_IMAGE_SCN_CNT_INITIALIZED_DATA |
600 EFI_IMAGE_SCN_MEM_NOT_PAGED |
601 EFI_IMAGE_SCN_MEM_READ );
602 debug->fixup = fixup_debug_section;
603
604 /* Create section contents */
605 contents->debug.TimeDateStamp = 0x10d1a884;
606 contents->debug.Type = EFI_IMAGE_DEBUG_TYPE_CODEVIEW;
607 contents->debug.SizeOfData =
608 ( sizeof ( *contents ) - sizeof ( contents->debug ) );
609 contents->debug.RVA = ( debug->hdr.VirtualAddress +
610 offsetof ( typeof ( *contents ), rsds ) );
611 contents->debug.FileOffset = contents->debug.RVA;
612 contents->rsds.Signature = CODEVIEW_SIGNATURE_RSDS;
613 snprintf ( contents->name, sizeof ( contents->name ), "%s",
614 filename );
615
616 /* Update file header details */
617 pe_header->nt.FileHeader.NumberOfSections++;
618 pe_header->nt.OptionalHeader.SizeOfHeaders += sizeof ( debug->hdr );
619 pe_header->nt.OptionalHeader.SizeOfImage += section_filesz;
620 debugdir = &(pe_header->nt.OptionalHeader.DataDirectory
621 [EFI_IMAGE_DIRECTORY_ENTRY_DEBUG]);
622 debugdir->VirtualAddress = debug->hdr.VirtualAddress;
623 debugdir->Size = sizeof ( contents->debug );
624
625 return debug;
626 }
627
628 /**
629 * Write out PE file
630 *
631 * @v pe_header PE file header
632 * @v pe_sections List of PE sections
633 * @v pe Output file
634 */
635 static void write_pe_file ( struct pe_header *pe_header,
636 struct pe_section *pe_sections,
637 FILE *pe ) {
638 struct pe_section *section;
639 unsigned long fpos = 0;
640
641 /* Align length of headers */
642 fpos = pe_header->nt.OptionalHeader.SizeOfHeaders =
643 efi_file_align ( pe_header->nt.OptionalHeader.SizeOfHeaders );
644
645 /* Assign raw data pointers */
646 for ( section = pe_sections ; section ; section = section->next ) {
647 if ( section->hdr.SizeOfRawData ) {
648 section->hdr.PointerToRawData = fpos;
649 fpos += section->hdr.SizeOfRawData;
650 fpos = efi_file_align ( fpos );
651 }
652 if ( section->fixup )
653 section->fixup ( section );
654 }
655
656 /* Write file header */
657 if ( fwrite ( pe_header, sizeof ( *pe_header ), 1, pe ) != 1 ) {
658 perror ( "Could not write PE header" );
659 exit ( 1 );
660 }
661
662 /* Write section headers */
663 for ( section = pe_sections ; section ; section = section->next ) {
664 if ( fwrite ( &section->hdr, sizeof ( section->hdr ),
665 1, pe ) != 1 ) {
666 perror ( "Could not write section header" );
667 exit ( 1 );
668 }
669 }
670
671 /* Write sections */
672 for ( section = pe_sections ; section ; section = section->next ) {
673 if ( fseek ( pe, section->hdr.PointerToRawData,
674 SEEK_SET ) != 0 ) {
675 eprintf ( "Could not seek to %x: %s\n",
676 section->hdr.PointerToRawData,
677 strerror ( errno ) );
678 exit ( 1 );
679 }
680 if ( section->hdr.SizeOfRawData &&
681 ( fwrite ( section->contents, section->hdr.SizeOfRawData,
682 1, pe ) != 1 ) ) {
683 eprintf ( "Could not write section %.8s: %s\n",
684 section->hdr.Name, strerror ( errno ) );
685 exit ( 1 );
686 }
687 }
688 }
689
690 /**
691 * Convert ELF to PE
692 *
693 * @v elf_name ELF file name
694 * @v pe_name PE file name
695 */
696 static void elf2pe ( const char *elf_name, const char *pe_name,
697 struct options *opts ) {
698 char pe_name_tmp[ strlen ( pe_name ) + 1 ];
699 bfd *bfd;
700 asymbol **symtab;
701 asection *section;
702 arelent **reltab;
703 arelent **rel;
704 struct pe_relocs *pe_reltab = NULL;
705 struct pe_section *pe_sections = NULL;
706 struct pe_section **next_pe_section = &pe_sections;
707 struct pe_header pe_header;
708 FILE *pe;
709
710 /* Create a modifiable copy of the PE name */
711 memcpy ( pe_name_tmp, pe_name, sizeof ( pe_name_tmp ) );
712
713 /* Open the file */
714 bfd = open_input_bfd ( elf_name );
715 symtab = read_symtab ( bfd );
716
717 /* Initialise the PE header */
718 memcpy ( &pe_header, &efi_pe_header, sizeof ( pe_header ) );
719 pe_header.nt.OptionalHeader.AddressOfEntryPoint =
720 bfd_get_start_address ( bfd );
721 pe_header.nt.OptionalHeader.Subsystem = opts->subsystem;
722
723 /* For each input section, build an output section and create
724 * the appropriate relocation records
725 */
726 for ( section = bfd->sections ; section ; section = section->next ) {
727 /* Discard non-allocatable sections */
728 if ( ! ( bfd_get_section_flags ( bfd, section ) & SEC_ALLOC ) )
729 continue;
730 /* Create output section */
731 *(next_pe_section) = process_section ( bfd, &pe_header,
732 section );
733 next_pe_section = &(*next_pe_section)->next;
734 /* Add relocations from this section */
735 reltab = read_reltab ( bfd, symtab, section );
736 for ( rel = reltab ; *rel ; rel++ )
737 process_reloc ( bfd, section, *rel, &pe_reltab );
738 free ( reltab );
739 }
740
741 /* Create the .reloc section */
742 *(next_pe_section) = create_reloc_section ( &pe_header, pe_reltab );
743 next_pe_section = &(*next_pe_section)->next;
744
745 /* Create the .reloc section */
746 *(next_pe_section) = create_debug_section ( &pe_header,
747 basename ( pe_name_tmp ) );
748 next_pe_section = &(*next_pe_section)->next;
749
750 /* Write out PE file */
751 pe = fopen ( pe_name, "w" );
752 if ( ! pe ) {
753 eprintf ( "Could not open %s for writing: %s\n",
754 pe_name, strerror ( errno ) );
755 exit ( 1 );
756 }
757 write_pe_file ( &pe_header, pe_sections, pe );
758 fclose ( pe );
759
760 /* Close BFD file */
761 bfd_close ( bfd );
762 }
763
764 /**
765 * Print help
766 *
767 * @v program_name Program name
768 */
769 static void print_help ( const char *program_name ) {
770 eprintf ( "Syntax: %s [--subsystem=<number>] infile outfile\n",
771 program_name );
772 }
773
774 /**
775 * Parse command-line options
776 *
777 * @v argc Argument count
778 * @v argv Argument list
779 * @v opts Options structure to populate
780 */
781 static int parse_options ( const int argc, char **argv,
782 struct options *opts ) {
783 char *end;
784 int c;
785
786 while (1) {
787 int option_index = 0;
788 static struct option long_options[] = {
789 { "subsystem", required_argument, NULL, 's' },
790 { "help", 0, NULL, 'h' },
791 { 0, 0, 0, 0 }
792 };
793
794 if ( ( c = getopt_long ( argc, argv, "s:h",
795 long_options,
796 &option_index ) ) == -1 ) {
797 break;
798 }
799
800 switch ( c ) {
801 case 's':
802 opts->subsystem = strtoul ( optarg, &end, 0 );
803 if ( *end ) {
804 eprintf ( "Invalid subsytem \"%s\"\n",
805 optarg );
806 exit ( 2 );
807 }
808 break;
809 case 'h':
810 print_help ( argv[0] );
811 exit ( 0 );
812 case '?':
813 default:
814 exit ( 2 );
815 }
816 }
817 return optind;
818 }
819
820 int main ( int argc, char **argv ) {
821 struct options opts = {
822 .subsystem = EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION,
823 };
824 int infile_index;
825 const char *infile;
826 const char *outfile;
827
828 /* Initialise libbfd */
829 bfd_init();
830
831 /* Parse command-line arguments */
832 infile_index = parse_options ( argc, argv, &opts );
833 if ( argc != ( infile_index + 2 ) ) {
834 print_help ( argv[0] );
835 exit ( 2 );
836 }
837 infile = argv[infile_index];
838 outfile = argv[infile_index + 1];
839
840 /* Convert file */
841 elf2pe ( infile, outfile, &opts );
842
843 return 0;
844 }