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

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