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 23KB

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