You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

elf2efi.c 22KB

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