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