Add qemu 2.4.0
[kvmfornfv.git] / qemu / roms / ipxe / 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_X86_64_64" ) == 0 ) {
482                 /* Generate an 8-byte PE relocation */
483                 generate_pe_reloc ( pe_reltab, offset, 8 );
484         } else if ( ( strcmp ( howto->name, "R_386_32" ) == 0 ) ||
485                     ( strcmp ( howto->name, "R_X86_64_32" ) == 0 ) ) {
486                 /* Generate a 4-byte PE relocation */
487                 generate_pe_reloc ( pe_reltab, offset, 4 );
488         } else if ( strcmp ( howto->name, "R_386_16" ) == 0 ) {
489                 /* Generate a 2-byte PE relocation */
490                 generate_pe_reloc ( pe_reltab, offset, 2 );
491         } else if ( ( strcmp ( howto->name, "R_386_PC32" ) == 0 ) ||
492                     ( strcmp ( howto->name, "R_X86_64_PC32" ) == 0 ) ) {
493                 /* Skip PC-relative relocations; all relative offsets
494                  * remain unaltered when the object is loaded.
495                  */
496         } else {
497                 eprintf ( "Unrecognised relocation type %s\n", howto->name );
498                 exit ( 1 );
499         }
500 }
501
502 /**
503  * Create relocations section
504  *
505  * @v pe_header         PE file header
506  * @v pe_reltab         PE relocation table
507  * @ret section         Relocation section
508  */
509 static struct pe_section *
510 create_reloc_section ( struct pe_header *pe_header,
511                        struct pe_relocs *pe_reltab ) {
512         struct pe_section *reloc;
513         size_t section_memsz;
514         size_t section_filesz;
515         EFI_IMAGE_DATA_DIRECTORY *relocdir;
516
517         /* Allocate PE section */
518         section_memsz = output_pe_reltab ( pe_reltab, NULL );
519         section_filesz = efi_file_align ( section_memsz );
520         reloc = xmalloc ( sizeof ( *reloc ) + section_filesz );
521         memset ( reloc, 0, sizeof ( *reloc ) + section_filesz );
522
523         /* Fill in section header details */
524         strncpy ( ( char * ) reloc->hdr.Name, ".reloc",
525                   sizeof ( reloc->hdr.Name ) );
526         reloc->hdr.Misc.VirtualSize = section_memsz;
527         reloc->hdr.VirtualAddress = pe_header->nt.OptionalHeader.SizeOfImage;
528         reloc->hdr.SizeOfRawData = section_filesz;
529         reloc->hdr.Characteristics = ( EFI_IMAGE_SCN_CNT_INITIALIZED_DATA |
530                                        EFI_IMAGE_SCN_MEM_NOT_PAGED |
531                                        EFI_IMAGE_SCN_MEM_READ );
532
533         /* Copy in section contents */
534         output_pe_reltab ( pe_reltab, reloc->contents );
535
536         /* Update file header details */
537         pe_header->nt.FileHeader.NumberOfSections++;
538         pe_header->nt.OptionalHeader.SizeOfHeaders += sizeof ( reloc->hdr );
539         pe_header->nt.OptionalHeader.SizeOfImage += section_filesz;
540         relocdir = &(pe_header->nt.OptionalHeader.DataDirectory
541                      [EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC]);
542         relocdir->VirtualAddress = reloc->hdr.VirtualAddress;
543         relocdir->Size = reloc->hdr.Misc.VirtualSize;
544
545         return reloc;
546 }
547
548 /**
549  * Create debug section
550  *
551  * @v pe_header         PE file header
552  * @ret section         Debug section
553  */
554 static struct pe_section *
555 create_debug_section ( struct pe_header *pe_header, const char *filename ) {
556         struct pe_section *debug;
557         size_t section_memsz;
558         size_t section_filesz;
559         EFI_IMAGE_DATA_DIRECTORY *debugdir;
560         struct {
561                 EFI_IMAGE_DEBUG_DIRECTORY_ENTRY debug;
562                 EFI_IMAGE_DEBUG_CODEVIEW_RSDS_ENTRY rsds;
563                 char name[ strlen ( filename ) + 1 ];
564         } *contents;
565
566         /* Allocate PE section */
567         section_memsz = sizeof ( *contents );
568         section_filesz = efi_file_align ( section_memsz );
569         debug = xmalloc ( sizeof ( *debug ) + section_filesz );
570         memset ( debug, 0, sizeof ( *debug ) + section_filesz );
571         contents = ( void * ) debug->contents;
572
573         /* Fill in section header details */
574         strncpy ( ( char * ) debug->hdr.Name, ".debug",
575                   sizeof ( debug->hdr.Name ) );
576         debug->hdr.Misc.VirtualSize = section_memsz;
577         debug->hdr.VirtualAddress = pe_header->nt.OptionalHeader.SizeOfImage;
578         debug->hdr.SizeOfRawData = section_filesz;
579         debug->hdr.Characteristics = ( EFI_IMAGE_SCN_CNT_INITIALIZED_DATA |
580                                        EFI_IMAGE_SCN_MEM_NOT_PAGED |
581                                        EFI_IMAGE_SCN_MEM_READ );
582
583         /* Create section contents */
584         contents->debug.TimeDateStamp = 0x10d1a884;
585         contents->debug.Type = EFI_IMAGE_DEBUG_TYPE_CODEVIEW;
586         contents->debug.SizeOfData =
587                 ( sizeof ( *contents ) - sizeof ( contents->debug ) );
588         contents->debug.RVA = ( debug->hdr.VirtualAddress +
589                                 offsetof ( typeof ( *contents ), rsds ) );
590         contents->rsds.Signature = CODEVIEW_SIGNATURE_RSDS;
591         snprintf ( contents->name, sizeof ( contents->name ), "%s",
592                    filename );
593
594         /* Update file header details */
595         pe_header->nt.FileHeader.NumberOfSections++;
596         pe_header->nt.OptionalHeader.SizeOfHeaders += sizeof ( debug->hdr );
597         pe_header->nt.OptionalHeader.SizeOfImage += section_filesz;
598         debugdir = &(pe_header->nt.OptionalHeader.DataDirectory
599                      [EFI_IMAGE_DIRECTORY_ENTRY_DEBUG]);
600         debugdir->VirtualAddress = debug->hdr.VirtualAddress;
601         debugdir->Size = debug->hdr.Misc.VirtualSize;
602
603         return debug;
604 }
605
606 /**
607  * Write out PE file
608  *
609  * @v pe_header         PE file header
610  * @v pe_sections       List of PE sections
611  * @v pe                Output file
612  */
613 static void write_pe_file ( struct pe_header *pe_header,
614                             struct pe_section *pe_sections,
615                             FILE *pe ) {
616         struct pe_section *section;
617         unsigned long fpos = 0;
618
619         /* Align length of headers */
620         fpos = pe_header->nt.OptionalHeader.SizeOfHeaders =
621                 efi_file_align ( pe_header->nt.OptionalHeader.SizeOfHeaders );
622
623         /* Assign raw data pointers */
624         for ( section = pe_sections ; section ; section = section->next ) {
625                 if ( section->hdr.SizeOfRawData ) {
626                         section->hdr.PointerToRawData = fpos;
627                         fpos += section->hdr.SizeOfRawData;
628                         fpos = efi_file_align ( fpos );
629                 }
630         }
631
632         /* Write file header */
633         if ( fwrite ( pe_header, sizeof ( *pe_header ), 1, pe ) != 1 ) {
634                 perror ( "Could not write PE header" );
635                 exit ( 1 );
636         }
637
638         /* Write section headers */
639         for ( section = pe_sections ; section ; section = section->next ) {
640                 if ( fwrite ( &section->hdr, sizeof ( section->hdr ),
641                               1, pe ) != 1 ) {
642                         perror ( "Could not write section header" );
643                         exit ( 1 );
644                 }
645         }
646
647         /* Write sections */
648         for ( section = pe_sections ; section ; section = section->next ) {
649                 if ( fseek ( pe, section->hdr.PointerToRawData,
650                              SEEK_SET ) != 0 ) {
651                         eprintf ( "Could not seek to %x: %s\n",
652                                   section->hdr.PointerToRawData,
653                                   strerror ( errno ) );
654                         exit ( 1 );
655                 }
656                 if ( section->hdr.SizeOfRawData &&
657                      ( fwrite ( section->contents, section->hdr.SizeOfRawData,
658                                 1, pe ) != 1 ) ) {
659                         eprintf ( "Could not write section %.8s: %s\n",
660                                   section->hdr.Name, strerror ( errno ) );
661                         exit ( 1 );
662                 }
663         }
664 }
665
666 /**
667  * Convert ELF to PE
668  *
669  * @v elf_name          ELF file name
670  * @v pe_name           PE file name
671  */
672 static void elf2pe ( const char *elf_name, const char *pe_name,
673                      struct options *opts ) {
674         char pe_name_tmp[ strlen ( pe_name ) + 1 ];
675         bfd *bfd;
676         asymbol **symtab;
677         asection *section;
678         arelent **reltab;
679         arelent **rel;
680         struct pe_relocs *pe_reltab = NULL;
681         struct pe_section *pe_sections = NULL;
682         struct pe_section **next_pe_section = &pe_sections;
683         struct pe_header pe_header;
684         FILE *pe;
685
686         /* Create a modifiable copy of the PE name */
687         memcpy ( pe_name_tmp, pe_name, sizeof ( pe_name_tmp ) );
688
689         /* Open the file */
690         bfd = open_input_bfd ( elf_name );
691         symtab = read_symtab ( bfd );
692
693         /* Initialise the PE header */
694         memcpy ( &pe_header, &efi_pe_header, sizeof ( pe_header ) );
695         pe_header.nt.OptionalHeader.AddressOfEntryPoint =
696                 bfd_get_start_address ( bfd );
697         pe_header.nt.OptionalHeader.Subsystem = opts->subsystem;
698
699         /* For each input section, build an output section and create
700          * the appropriate relocation records
701          */
702         for ( section = bfd->sections ; section ; section = section->next ) {
703                 /* Discard non-allocatable sections */
704                 if ( ! ( bfd_get_section_flags ( bfd, section ) & SEC_ALLOC ) )
705                         continue;
706                 /* Create output section */
707                 *(next_pe_section) = process_section ( bfd, &pe_header,
708                                                        section );
709                 next_pe_section = &(*next_pe_section)->next;
710                 /* Add relocations from this section */
711                 reltab = read_reltab ( bfd, symtab, section );
712                 for ( rel = reltab ; *rel ; rel++ )
713                         process_reloc ( bfd, section, *rel, &pe_reltab );
714                 free ( reltab );
715         }
716
717         /* Create the .reloc section */
718         *(next_pe_section) = create_reloc_section ( &pe_header, pe_reltab );
719         next_pe_section = &(*next_pe_section)->next;
720
721         /* Create the .reloc section */
722         *(next_pe_section) = create_debug_section ( &pe_header,
723                                                     basename ( pe_name_tmp ) );
724         next_pe_section = &(*next_pe_section)->next;
725
726         /* Write out PE file */
727         pe = fopen ( pe_name, "w" );
728         if ( ! pe ) {
729                 eprintf ( "Could not open %s for writing: %s\n",
730                           pe_name, strerror ( errno ) );
731                 exit ( 1 );
732         }
733         write_pe_file ( &pe_header, pe_sections, pe );
734         fclose ( pe );
735
736         /* Close BFD file */
737         bfd_close ( bfd );
738 }
739
740 /**
741  * Print help
742  *
743  * @v program_name      Program name
744  */
745 static void print_help ( const char *program_name ) {
746         eprintf ( "Syntax: %s [--subsystem=<number>] infile outfile\n",
747                   program_name );
748 }
749
750 /**
751  * Parse command-line options
752  *
753  * @v argc              Argument count
754  * @v argv              Argument list
755  * @v opts              Options structure to populate
756  */
757 static int parse_options ( const int argc, char **argv,
758                            struct options *opts ) {
759         char *end;
760         int c;
761
762         while (1) {
763                 int option_index = 0;
764                 static struct option long_options[] = {
765                         { "subsystem", required_argument, NULL, 's' },
766                         { "help", 0, NULL, 'h' },
767                         { 0, 0, 0, 0 }
768                 };
769
770                 if ( ( c = getopt_long ( argc, argv, "s:h",
771                                          long_options,
772                                          &option_index ) ) == -1 ) {
773                         break;
774                 }
775
776                 switch ( c ) {
777                 case 's':
778                         opts->subsystem = strtoul ( optarg, &end, 0 );
779                         if ( *end ) {
780                                 eprintf ( "Invalid subsytem \"%s\"\n",
781                                           optarg );
782                                 exit ( 2 );
783                         }
784                         break;
785                 case 'h':
786                         print_help ( argv[0] );
787                         exit ( 0 );
788                 case '?':
789                 default:
790                         exit ( 2 );
791                 }
792         }
793         return optind;
794 }
795
796 int main ( int argc, char **argv ) {
797         struct options opts = {
798                 .subsystem = EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION,
799         };
800         int infile_index;
801         const char *infile;
802         const char *outfile;
803
804         /* Initialise libbfd */
805         bfd_init();
806
807         /* Parse command-line arguments */
808         infile_index = parse_options ( argc, argv, &opts );
809         if ( argc != ( infile_index + 2 ) ) {
810                 print_help ( argv[0] );
811                 exit ( 2 );
812         }
813         infile = argv[infile_index];
814         outfile = argv[infile_index + 1];
815
816         /* Convert file */
817         elf2pe ( infile, outfile, &opts );
818
819         return 0;
820 }