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

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