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

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