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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032
  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 FILE_LICENCE(...) extern void __file_licence ( void )
  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 <sys/types.h>
  30. #include <sys/stat.h>
  31. #include <sys/mman.h>
  32. #include <fcntl.h>
  33. #include <elf.h>
  34. #include <libgen.h>
  35. #include <ipxe/efi/Uefi.h>
  36. #include <ipxe/efi/IndustryStandard/PeImage.h>
  37. #define eprintf(...) fprintf ( stderr, __VA_ARGS__ )
  38. #ifdef EFI_TARGET32
  39. #define EFI_IMAGE_NT_HEADERS EFI_IMAGE_NT_HEADERS32
  40. #define EFI_IMAGE_NT_OPTIONAL_HDR_MAGIC EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
  41. #define EFI_IMAGE_FILE_MACHINE EFI_IMAGE_FILE_32BIT_MACHINE
  42. #define ELFCLASS ELFCLASS32
  43. #define Elf_Ehdr Elf32_Ehdr
  44. #define Elf_Shdr Elf32_Shdr
  45. #define Elf_Sym Elf32_Sym
  46. #define Elf_Addr Elf32_Addr
  47. #define Elf_Rel Elf32_Rel
  48. #define Elf_Rela Elf32_Rela
  49. #define ELF_R_TYPE ELF32_R_TYPE
  50. #define ELF_R_SYM ELF32_R_SYM
  51. #elif defined(EFI_TARGET64)
  52. #define EFI_IMAGE_NT_HEADERS EFI_IMAGE_NT_HEADERS64
  53. #define EFI_IMAGE_NT_OPTIONAL_HDR_MAGIC EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
  54. #define EFI_IMAGE_FILE_MACHINE 0
  55. #define ELFCLASS ELFCLASS64
  56. #define Elf_Ehdr Elf64_Ehdr
  57. #define Elf_Shdr Elf64_Shdr
  58. #define Elf_Sym Elf64_Sym
  59. #define Elf_Addr Elf64_Addr
  60. #define Elf_Rel Elf64_Rel
  61. #define Elf_Rela Elf64_Rela
  62. #define ELF_R_TYPE ELF64_R_TYPE
  63. #define ELF_R_SYM ELF64_R_SYM
  64. #endif
  65. #define ELF_MREL( mach, type ) ( (mach) | ( (type) << 16 ) )
  66. /* Allow for building with older versions of elf.h */
  67. #ifndef EM_AARCH64
  68. #define EM_AARCH64 183
  69. #define R_AARCH64_NONE 0
  70. #define R_AARCH64_ABS64 257
  71. #define R_AARCH64_CALL26 283
  72. #define R_AARCH64_JUMP26 282
  73. #define R_AARCH64_ADR_PREL_LO21 274
  74. #define R_AARCH64_ADR_PREL_PG_HI21 275
  75. #define R_AARCH64_ADD_ABS_LO12_NC 277
  76. #define R_AARCH64_LDST8_ABS_LO12_NC 278
  77. #define R_AARCH64_LDST16_ABS_LO12_NC 284
  78. #define R_AARCH64_LDST32_ABS_LO12_NC 285
  79. #define R_AARCH64_LDST64_ABS_LO12_NC 286
  80. #endif /* EM_AARCH64 */
  81. #ifndef R_ARM_CALL
  82. #define R_ARM_CALL 28
  83. #endif
  84. #ifndef R_ARM_THM_JUMP24
  85. #define R_ARM_THM_JUMP24 30
  86. #endif
  87. #ifndef R_ARM_V4BX
  88. #define R_ARM_V4BX 40
  89. #endif
  90. /* Seems to be missing from elf.h */
  91. #ifndef R_AARCH64_NULL
  92. #define R_AARCH64_NULL 256
  93. #endif
  94. #define EFI_FILE_ALIGN 0x20
  95. struct elf_file {
  96. void *data;
  97. size_t len;
  98. const Elf_Ehdr *ehdr;
  99. };
  100. struct pe_section {
  101. struct pe_section *next;
  102. EFI_IMAGE_SECTION_HEADER hdr;
  103. void ( * fixup ) ( struct pe_section *section );
  104. uint8_t contents[0];
  105. };
  106. struct pe_relocs {
  107. struct pe_relocs *next;
  108. unsigned long start_rva;
  109. unsigned int used_relocs;
  110. unsigned int total_relocs;
  111. uint16_t *relocs;
  112. };
  113. struct pe_header {
  114. EFI_IMAGE_DOS_HEADER dos;
  115. uint8_t padding[128];
  116. EFI_IMAGE_NT_HEADERS nt;
  117. };
  118. static struct pe_header efi_pe_header = {
  119. .dos = {
  120. .e_magic = EFI_IMAGE_DOS_SIGNATURE,
  121. .e_lfanew = offsetof ( typeof ( efi_pe_header ), nt ),
  122. },
  123. .nt = {
  124. .Signature = EFI_IMAGE_NT_SIGNATURE,
  125. .FileHeader = {
  126. .TimeDateStamp = 0x10d1a884,
  127. .SizeOfOptionalHeader =
  128. sizeof ( efi_pe_header.nt.OptionalHeader ),
  129. .Characteristics = ( EFI_IMAGE_FILE_DLL |
  130. EFI_IMAGE_FILE_MACHINE |
  131. EFI_IMAGE_FILE_EXECUTABLE_IMAGE ),
  132. },
  133. .OptionalHeader = {
  134. .Magic = EFI_IMAGE_NT_OPTIONAL_HDR_MAGIC,
  135. .MajorLinkerVersion = 42,
  136. .MinorLinkerVersion = 42,
  137. .SectionAlignment = EFI_FILE_ALIGN,
  138. .FileAlignment = EFI_FILE_ALIGN,
  139. .SizeOfImage = sizeof ( efi_pe_header ),
  140. .SizeOfHeaders = sizeof ( efi_pe_header ),
  141. .NumberOfRvaAndSizes =
  142. EFI_IMAGE_NUMBER_OF_DIRECTORY_ENTRIES,
  143. },
  144. },
  145. };
  146. /** Command-line options */
  147. struct options {
  148. unsigned int subsystem;
  149. };
  150. /**
  151. * Allocate memory
  152. *
  153. * @v len Length of memory to allocate
  154. * @ret ptr Pointer to allocated memory
  155. */
  156. static void * xmalloc ( size_t len ) {
  157. void *ptr;
  158. ptr = malloc ( len );
  159. if ( ! ptr ) {
  160. eprintf ( "Could not allocate %zd bytes\n", len );
  161. exit ( 1 );
  162. }
  163. return ptr;
  164. }
  165. /**
  166. * Align section within PE file
  167. *
  168. * @v offset Unaligned offset
  169. * @ret aligned_offset Aligned offset
  170. */
  171. static unsigned long efi_file_align ( unsigned long offset ) {
  172. return ( ( offset + EFI_FILE_ALIGN - 1 ) & ~( EFI_FILE_ALIGN - 1 ) );
  173. }
  174. /**
  175. * Generate entry in PE relocation table
  176. *
  177. * @v pe_reltab PE relocation table
  178. * @v rva RVA
  179. * @v size Size of relocation entry
  180. */
  181. static void generate_pe_reloc ( struct pe_relocs **pe_reltab,
  182. unsigned long rva, size_t size ) {
  183. unsigned long start_rva;
  184. uint16_t reloc;
  185. struct pe_relocs *pe_rel;
  186. uint16_t *relocs;
  187. /* Construct */
  188. start_rva = ( rva & ~0xfff );
  189. reloc = ( rva & 0xfff );
  190. switch ( size ) {
  191. case 8:
  192. reloc |= 0xa000;
  193. break;
  194. case 4:
  195. reloc |= 0x3000;
  196. break;
  197. case 2:
  198. reloc |= 0x2000;
  199. break;
  200. default:
  201. eprintf ( "Unsupported relocation size %zd\n", size );
  202. exit ( 1 );
  203. }
  204. /* Locate or create PE relocation table */
  205. for ( pe_rel = *pe_reltab ; pe_rel ; pe_rel = pe_rel->next ) {
  206. if ( pe_rel->start_rva == start_rva )
  207. break;
  208. }
  209. if ( ! pe_rel ) {
  210. pe_rel = xmalloc ( sizeof ( *pe_rel ) );
  211. memset ( pe_rel, 0, sizeof ( *pe_rel ) );
  212. pe_rel->next = *pe_reltab;
  213. *pe_reltab = pe_rel;
  214. pe_rel->start_rva = start_rva;
  215. }
  216. /* Expand relocation list if necessary */
  217. if ( pe_rel->used_relocs < pe_rel->total_relocs ) {
  218. relocs = pe_rel->relocs;
  219. } else {
  220. pe_rel->total_relocs = ( pe_rel->total_relocs ?
  221. ( pe_rel->total_relocs * 2 ) : 256 );
  222. relocs = xmalloc ( pe_rel->total_relocs *
  223. sizeof ( pe_rel->relocs[0] ) );
  224. memset ( relocs, 0,
  225. pe_rel->total_relocs * sizeof ( pe_rel->relocs[0] ) );
  226. memcpy ( relocs, pe_rel->relocs,
  227. pe_rel->used_relocs * sizeof ( pe_rel->relocs[0] ) );
  228. free ( pe_rel->relocs );
  229. pe_rel->relocs = relocs;
  230. }
  231. /* Store relocation */
  232. pe_rel->relocs[ pe_rel->used_relocs++ ] = reloc;
  233. }
  234. /**
  235. * Calculate size of binary PE relocation table
  236. *
  237. * @v pe_reltab PE relocation table
  238. * @v buffer Buffer to contain binary table, or NULL
  239. * @ret size Size of binary table
  240. */
  241. static size_t output_pe_reltab ( struct pe_relocs *pe_reltab,
  242. void *buffer ) {
  243. struct pe_relocs *pe_rel;
  244. unsigned int num_relocs;
  245. size_t size;
  246. size_t total_size = 0;
  247. for ( pe_rel = pe_reltab ; pe_rel ; pe_rel = pe_rel->next ) {
  248. num_relocs = ( ( pe_rel->used_relocs + 1 ) & ~1 );
  249. size = ( sizeof ( uint32_t ) /* VirtualAddress */ +
  250. sizeof ( uint32_t ) /* SizeOfBlock */ +
  251. ( num_relocs * sizeof ( uint16_t ) ) );
  252. if ( buffer ) {
  253. *( (uint32_t *) ( buffer + total_size + 0 ) )
  254. = pe_rel->start_rva;
  255. *( (uint32_t *) ( buffer + total_size + 4 ) ) = size;
  256. memcpy ( ( buffer + total_size + 8 ), pe_rel->relocs,
  257. ( num_relocs * sizeof ( uint16_t ) ) );
  258. }
  259. total_size += size;
  260. }
  261. return total_size;
  262. }
  263. /**
  264. * Read input ELF file
  265. *
  266. * @v name File name
  267. * @v elf ELF file
  268. */
  269. static void read_elf_file ( const char *name, struct elf_file *elf ) {
  270. static const unsigned char ident[] = {
  271. ELFMAG0, ELFMAG1, ELFMAG2, ELFMAG3, ELFCLASS, ELFDATA2LSB
  272. };
  273. struct stat stat;
  274. const Elf_Ehdr *ehdr;
  275. const Elf_Shdr *shdr;
  276. void *data;
  277. size_t offset;
  278. unsigned int i;
  279. int fd;
  280. /* Open file */
  281. fd = open ( name, O_RDONLY );
  282. if ( fd < 0 ) {
  283. eprintf ( "Could not open %s: %s\n", name, strerror ( errno ) );
  284. exit ( 1 );
  285. }
  286. /* Get file size */
  287. if ( fstat ( fd, &stat ) < 0 ) {
  288. eprintf ( "Could not get size of %s: %s\n",
  289. name, strerror ( errno ) );
  290. exit ( 1 );
  291. }
  292. elf->len = stat.st_size;
  293. /* Map file */
  294. data = mmap ( NULL, elf->len, PROT_READ, MAP_SHARED, fd, 0 );
  295. if ( data == MAP_FAILED ) {
  296. eprintf ( "Could not map %s: %s\n", name, strerror ( errno ) );
  297. exit ( 1 );
  298. }
  299. elf->data = data;
  300. /* Close file */
  301. close ( fd );
  302. /* Check header */
  303. ehdr = elf->data;
  304. if ( ( elf->len < sizeof ( *ehdr ) ) ||
  305. ( memcmp ( ident, ehdr->e_ident, sizeof ( ident ) ) != 0 ) ) {
  306. eprintf ( "Invalid ELF header in %s\n", name );
  307. exit ( 1 );
  308. }
  309. elf->ehdr = ehdr;
  310. /* Check section headers */
  311. for ( i = 0 ; i < ehdr->e_shnum ; i++ ) {
  312. offset = ( ehdr->e_shoff + ( i * ehdr->e_shentsize ) );
  313. if ( elf->len < ( offset + sizeof ( *shdr ) ) ) {
  314. eprintf ( "ELF section header outside file in %s\n",
  315. name );
  316. exit ( 1 );
  317. }
  318. shdr = ( data + offset );
  319. if ( ( shdr->sh_type != SHT_NOBITS ) &&
  320. ( ( elf->len < shdr->sh_offset ) ||
  321. ( ( ( elf->len - shdr->sh_offset ) < shdr->sh_size ) ))){
  322. eprintf ( "ELF section %d outside file in %s\n",
  323. i, name );
  324. exit ( 1 );
  325. }
  326. if ( shdr->sh_link >= ehdr->e_shnum ) {
  327. eprintf ( "ELF section %d link section %d out of "
  328. "range\n", i, shdr->sh_link );
  329. exit ( 1 );
  330. }
  331. }
  332. }
  333. /**
  334. * Get ELF string
  335. *
  336. * @v elf ELF file
  337. * @v section String table section number
  338. * @v offset String table offset
  339. * @ret string ELF string
  340. */
  341. static const char * elf_string ( struct elf_file *elf, unsigned int section,
  342. size_t offset ) {
  343. const Elf_Ehdr *ehdr = elf->ehdr;
  344. const Elf_Shdr *shdr;
  345. char *string;
  346. char *last;
  347. /* Locate section header */
  348. if ( section >= ehdr->e_shnum ) {
  349. eprintf ( "Invalid ELF string section %d\n", section );
  350. exit ( 1 );
  351. }
  352. shdr = ( elf->data + ehdr->e_shoff + ( section * ehdr->e_shentsize ) );
  353. /* Sanity check section */
  354. if ( shdr->sh_type != SHT_STRTAB ) {
  355. eprintf ( "ELF section %d (type %d) is not a string table\n",
  356. section, shdr->sh_type );
  357. exit ( 1 );
  358. }
  359. last = ( elf->data + shdr->sh_offset + shdr->sh_size - 1 );
  360. if ( *last != '\0' ) {
  361. eprintf ( "ELF section %d is not NUL-terminated\n", section );
  362. exit ( 1 );
  363. }
  364. /* Locate string */
  365. if ( offset >= shdr->sh_size ) {
  366. eprintf ( "Invalid ELF string offset %zd in section %d\n",
  367. offset, section );
  368. exit ( 1 );
  369. }
  370. string = ( elf->data + shdr->sh_offset + offset );
  371. return string;
  372. }
  373. /**
  374. * Set machine architecture
  375. *
  376. * @v elf ELF file
  377. * @v pe_header PE file header
  378. */
  379. static void set_machine ( struct elf_file *elf, struct pe_header *pe_header ) {
  380. const Elf_Ehdr *ehdr = elf->ehdr;
  381. uint16_t machine;
  382. /* Identify machine architecture */
  383. switch ( ehdr->e_machine ) {
  384. case EM_386:
  385. machine = EFI_IMAGE_MACHINE_IA32;
  386. break;
  387. case EM_X86_64:
  388. machine = EFI_IMAGE_MACHINE_X64;
  389. break;
  390. case EM_ARM:
  391. machine = EFI_IMAGE_MACHINE_ARMTHUMB_MIXED;
  392. break;
  393. case EM_AARCH64:
  394. machine = EFI_IMAGE_MACHINE_AARCH64;
  395. break;
  396. default:
  397. eprintf ( "Unknown ELF architecture %d\n", ehdr->e_machine );
  398. exit ( 1 );
  399. }
  400. /* Set machine architecture */
  401. pe_header->nt.FileHeader.Machine = machine;
  402. }
  403. /**
  404. * Process section
  405. *
  406. * @v elf ELF file
  407. * @v shdr ELF section header
  408. * @v pe_header PE file header
  409. * @ret new New PE section
  410. */
  411. static struct pe_section * process_section ( struct elf_file *elf,
  412. const Elf_Shdr *shdr,
  413. struct pe_header *pe_header ) {
  414. struct pe_section *new;
  415. const char *name;
  416. size_t section_memsz;
  417. size_t section_filesz;
  418. unsigned long code_start;
  419. unsigned long code_end;
  420. unsigned long data_start;
  421. unsigned long data_mid;
  422. unsigned long data_end;
  423. unsigned long start;
  424. unsigned long end;
  425. unsigned long *applicable_start;
  426. unsigned long *applicable_end;
  427. /* Get section name */
  428. name = elf_string ( elf, elf->ehdr->e_shstrndx, shdr->sh_name );
  429. /* Extract current RVA limits from file header */
  430. code_start = pe_header->nt.OptionalHeader.BaseOfCode;
  431. code_end = ( code_start + pe_header->nt.OptionalHeader.SizeOfCode );
  432. #if defined(EFI_TARGET32)
  433. data_start = pe_header->nt.OptionalHeader.BaseOfData;
  434. #elif defined(EFI_TARGET64)
  435. data_start = code_end;
  436. #endif
  437. data_mid = ( data_start +
  438. pe_header->nt.OptionalHeader.SizeOfInitializedData );
  439. data_end = ( data_mid +
  440. pe_header->nt.OptionalHeader.SizeOfUninitializedData );
  441. /* Allocate PE section */
  442. section_memsz = shdr->sh_size;
  443. section_filesz = ( ( shdr->sh_type == SHT_PROGBITS ) ?
  444. efi_file_align ( section_memsz ) : 0 );
  445. new = xmalloc ( sizeof ( *new ) + section_filesz );
  446. memset ( new, 0, sizeof ( *new ) + section_filesz );
  447. /* Fill in section header details */
  448. strncpy ( ( char * ) new->hdr.Name, name, sizeof ( new->hdr.Name ) );
  449. new->hdr.Misc.VirtualSize = section_memsz;
  450. new->hdr.VirtualAddress = shdr->sh_addr;
  451. new->hdr.SizeOfRawData = section_filesz;
  452. /* Fill in section characteristics and update RVA limits */
  453. if ( ( shdr->sh_type == SHT_PROGBITS ) &&
  454. ( shdr->sh_flags & SHF_EXECINSTR ) ) {
  455. /* .text-type section */
  456. new->hdr.Characteristics =
  457. ( EFI_IMAGE_SCN_CNT_CODE |
  458. EFI_IMAGE_SCN_MEM_NOT_PAGED |
  459. EFI_IMAGE_SCN_MEM_EXECUTE |
  460. EFI_IMAGE_SCN_MEM_READ );
  461. applicable_start = &code_start;
  462. applicable_end = &code_end;
  463. } else if ( ( shdr->sh_type == SHT_PROGBITS ) &&
  464. ( shdr->sh_flags & SHF_WRITE ) ) {
  465. /* .data-type section */
  466. new->hdr.Characteristics =
  467. ( EFI_IMAGE_SCN_CNT_INITIALIZED_DATA |
  468. EFI_IMAGE_SCN_MEM_NOT_PAGED |
  469. EFI_IMAGE_SCN_MEM_READ |
  470. EFI_IMAGE_SCN_MEM_WRITE );
  471. applicable_start = &data_start;
  472. applicable_end = &data_mid;
  473. } else if ( shdr->sh_type == SHT_PROGBITS ) {
  474. /* .rodata-type section */
  475. new->hdr.Characteristics =
  476. ( EFI_IMAGE_SCN_CNT_INITIALIZED_DATA |
  477. EFI_IMAGE_SCN_MEM_NOT_PAGED |
  478. EFI_IMAGE_SCN_MEM_READ );
  479. applicable_start = &data_start;
  480. applicable_end = &data_mid;
  481. } else if ( shdr->sh_type == SHT_NOBITS ) {
  482. /* .bss-type section */
  483. new->hdr.Characteristics =
  484. ( EFI_IMAGE_SCN_CNT_UNINITIALIZED_DATA |
  485. EFI_IMAGE_SCN_MEM_NOT_PAGED |
  486. EFI_IMAGE_SCN_MEM_READ |
  487. EFI_IMAGE_SCN_MEM_WRITE );
  488. applicable_start = &data_mid;
  489. applicable_end = &data_end;
  490. } else {
  491. eprintf ( "Unrecognised characteristics for section %s\n",
  492. name );
  493. exit ( 1 );
  494. }
  495. /* Copy in section contents */
  496. if ( shdr->sh_type == SHT_PROGBITS ) {
  497. memcpy ( new->contents, ( elf->data + shdr->sh_offset ),
  498. shdr->sh_size );
  499. }
  500. /* Update RVA limits */
  501. start = new->hdr.VirtualAddress;
  502. end = ( start + new->hdr.Misc.VirtualSize );
  503. if ( ( ! *applicable_start ) || ( *applicable_start >= start ) )
  504. *applicable_start = start;
  505. if ( *applicable_end < end )
  506. *applicable_end = end;
  507. if ( data_start < code_end )
  508. data_start = code_end;
  509. if ( data_mid < data_start )
  510. data_mid = data_start;
  511. if ( data_end < data_mid )
  512. data_end = data_mid;
  513. /* Write RVA limits back to file header */
  514. pe_header->nt.OptionalHeader.BaseOfCode = code_start;
  515. pe_header->nt.OptionalHeader.SizeOfCode = ( code_end - code_start );
  516. #if defined(EFI_TARGET32)
  517. pe_header->nt.OptionalHeader.BaseOfData = data_start;
  518. #endif
  519. pe_header->nt.OptionalHeader.SizeOfInitializedData =
  520. ( data_mid - data_start );
  521. pe_header->nt.OptionalHeader.SizeOfUninitializedData =
  522. ( data_end - data_mid );
  523. /* Update remaining file header fields */
  524. pe_header->nt.FileHeader.NumberOfSections++;
  525. pe_header->nt.OptionalHeader.SizeOfHeaders += sizeof ( new->hdr );
  526. pe_header->nt.OptionalHeader.SizeOfImage =
  527. efi_file_align ( data_end );
  528. return new;
  529. }
  530. /**
  531. * Process relocation record
  532. *
  533. * @v elf ELF file
  534. * @v shdr ELF section header
  535. * @v syms Symbol table
  536. * @v nsyms Number of symbol table entries
  537. * @v rel Relocation record
  538. * @v pe_reltab PE relocation table to fill in
  539. */
  540. static void process_reloc ( struct elf_file *elf, const Elf_Shdr *shdr,
  541. const Elf_Sym *syms, unsigned int nsyms,
  542. const Elf_Rel *rel, struct pe_relocs **pe_reltab ) {
  543. unsigned int type = ELF_R_TYPE ( rel->r_info );
  544. unsigned int sym = ELF_R_SYM ( rel->r_info );
  545. unsigned int mrel = ELF_MREL ( elf->ehdr->e_machine, type );
  546. size_t offset = ( shdr->sh_addr + rel->r_offset );
  547. /* Look up symbol and process relocation */
  548. if ( sym >= nsyms ) {
  549. eprintf ( "Symbol out of range\n" );
  550. exit ( 1 );
  551. }
  552. if ( syms[sym].st_shndx == SHN_ABS ) {
  553. /* Skip absolute symbols; the symbol value won't
  554. * change when the object is loaded.
  555. */
  556. } else {
  557. switch ( mrel ) {
  558. case ELF_MREL ( EM_386, R_386_NONE ) :
  559. case ELF_MREL ( EM_ARM, R_ARM_NONE ) :
  560. case ELF_MREL ( EM_X86_64, R_X86_64_NONE ) :
  561. case ELF_MREL ( EM_AARCH64, R_AARCH64_NONE ) :
  562. case ELF_MREL ( EM_AARCH64, R_AARCH64_NULL ) :
  563. /* Ignore dummy relocations used by REQUIRE_SYMBOL() */
  564. break;
  565. case ELF_MREL ( EM_386, R_386_32 ) :
  566. case ELF_MREL ( EM_ARM, R_ARM_ABS32 ) :
  567. /* Generate a 4-byte PE relocation */
  568. generate_pe_reloc ( pe_reltab, offset, 4 );
  569. break;
  570. case ELF_MREL ( EM_X86_64, R_X86_64_64 ) :
  571. case ELF_MREL ( EM_AARCH64, R_AARCH64_ABS64 ) :
  572. /* Generate an 8-byte PE relocation */
  573. generate_pe_reloc ( pe_reltab, offset, 8 );
  574. break;
  575. case ELF_MREL ( EM_386, R_386_PC32 ) :
  576. case ELF_MREL ( EM_ARM, R_ARM_CALL ) :
  577. case ELF_MREL ( EM_ARM, R_ARM_REL32 ) :
  578. case ELF_MREL ( EM_ARM, R_ARM_THM_PC22 ) :
  579. case ELF_MREL ( EM_ARM, R_ARM_THM_JUMP24 ) :
  580. case ELF_MREL ( EM_ARM, R_ARM_V4BX ):
  581. case ELF_MREL ( EM_X86_64, R_X86_64_PC32 ) :
  582. case ELF_MREL ( EM_AARCH64, R_AARCH64_CALL26 ) :
  583. case ELF_MREL ( EM_AARCH64, R_AARCH64_JUMP26 ) :
  584. case ELF_MREL ( EM_AARCH64, R_AARCH64_ADR_PREL_LO21 ) :
  585. case ELF_MREL ( EM_AARCH64, R_AARCH64_ADR_PREL_PG_HI21 ) :
  586. case ELF_MREL ( EM_AARCH64, R_AARCH64_ADD_ABS_LO12_NC ) :
  587. case ELF_MREL ( EM_AARCH64, R_AARCH64_LDST8_ABS_LO12_NC ) :
  588. case ELF_MREL ( EM_AARCH64, R_AARCH64_LDST16_ABS_LO12_NC ) :
  589. case ELF_MREL ( EM_AARCH64, R_AARCH64_LDST32_ABS_LO12_NC ) :
  590. case ELF_MREL ( EM_AARCH64, R_AARCH64_LDST64_ABS_LO12_NC ) :
  591. /* Skip PC-relative relocations; all relative
  592. * offsets remain unaltered when the object is
  593. * loaded.
  594. */
  595. break;
  596. default:
  597. eprintf ( "Unrecognised relocation type %d\n", type );
  598. exit ( 1 );
  599. }
  600. }
  601. }
  602. /**
  603. * Process relocation records
  604. *
  605. * @v elf ELF file
  606. * @v shdr ELF section header
  607. * @v stride Relocation record size
  608. * @v pe_reltab PE relocation table to fill in
  609. */
  610. static void process_relocs ( struct elf_file *elf, const Elf_Shdr *shdr,
  611. size_t stride, struct pe_relocs **pe_reltab ) {
  612. const Elf_Shdr *symtab;
  613. const Elf_Sym *syms;
  614. const Elf_Rel *rel;
  615. unsigned int nsyms;
  616. unsigned int nrels;
  617. unsigned int i;
  618. /* Identify symbol table */
  619. symtab = ( elf->data + elf->ehdr->e_shoff +
  620. ( shdr->sh_link * elf->ehdr->e_shentsize ) );
  621. syms = ( elf->data + symtab->sh_offset );
  622. nsyms = ( symtab->sh_size / sizeof ( syms[0] ) );
  623. /* Process each relocation */
  624. rel = ( elf->data + shdr->sh_offset );
  625. nrels = ( shdr->sh_size / stride );
  626. for ( i = 0 ; i < nrels ; i++ ) {
  627. process_reloc ( elf, shdr, syms, nsyms, rel, pe_reltab );
  628. rel = ( ( ( const void * ) rel ) + stride );
  629. }
  630. }
  631. /**
  632. * Create relocations section
  633. *
  634. * @v pe_header PE file header
  635. * @v pe_reltab PE relocation table
  636. * @ret section Relocation section
  637. */
  638. static struct pe_section *
  639. create_reloc_section ( struct pe_header *pe_header,
  640. struct pe_relocs *pe_reltab ) {
  641. struct pe_section *reloc;
  642. size_t section_memsz;
  643. size_t section_filesz;
  644. EFI_IMAGE_DATA_DIRECTORY *relocdir;
  645. /* Allocate PE section */
  646. section_memsz = output_pe_reltab ( pe_reltab, NULL );
  647. section_filesz = efi_file_align ( section_memsz );
  648. reloc = xmalloc ( sizeof ( *reloc ) + section_filesz );
  649. memset ( reloc, 0, sizeof ( *reloc ) + section_filesz );
  650. /* Fill in section header details */
  651. strncpy ( ( char * ) reloc->hdr.Name, ".reloc",
  652. sizeof ( reloc->hdr.Name ) );
  653. reloc->hdr.Misc.VirtualSize = section_memsz;
  654. reloc->hdr.VirtualAddress = pe_header->nt.OptionalHeader.SizeOfImage;
  655. reloc->hdr.SizeOfRawData = section_filesz;
  656. reloc->hdr.Characteristics = ( EFI_IMAGE_SCN_CNT_INITIALIZED_DATA |
  657. EFI_IMAGE_SCN_MEM_NOT_PAGED |
  658. EFI_IMAGE_SCN_MEM_READ );
  659. /* Copy in section contents */
  660. output_pe_reltab ( pe_reltab, reloc->contents );
  661. /* Update file header details */
  662. pe_header->nt.FileHeader.NumberOfSections++;
  663. pe_header->nt.OptionalHeader.SizeOfHeaders += sizeof ( reloc->hdr );
  664. pe_header->nt.OptionalHeader.SizeOfImage += section_filesz;
  665. relocdir = &(pe_header->nt.OptionalHeader.DataDirectory
  666. [EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC]);
  667. relocdir->VirtualAddress = reloc->hdr.VirtualAddress;
  668. relocdir->Size = reloc->hdr.Misc.VirtualSize;
  669. return reloc;
  670. }
  671. /**
  672. * Fix up debug section
  673. *
  674. * @v debug Debug section
  675. */
  676. static void fixup_debug_section ( struct pe_section *debug ) {
  677. EFI_IMAGE_DEBUG_DIRECTORY_ENTRY *contents;
  678. /* Fix up FileOffset */
  679. contents = ( ( void * ) debug->contents );
  680. contents->FileOffset += ( debug->hdr.PointerToRawData -
  681. debug->hdr.VirtualAddress );
  682. }
  683. /**
  684. * Create debug section
  685. *
  686. * @v pe_header PE file header
  687. * @ret section Debug section
  688. */
  689. static struct pe_section *
  690. create_debug_section ( struct pe_header *pe_header, const char *filename ) {
  691. struct pe_section *debug;
  692. size_t section_memsz;
  693. size_t section_filesz;
  694. EFI_IMAGE_DATA_DIRECTORY *debugdir;
  695. struct {
  696. EFI_IMAGE_DEBUG_DIRECTORY_ENTRY debug;
  697. EFI_IMAGE_DEBUG_CODEVIEW_RSDS_ENTRY rsds;
  698. char name[ strlen ( filename ) + 1 ];
  699. } *contents;
  700. /* Allocate PE section */
  701. section_memsz = sizeof ( *contents );
  702. section_filesz = efi_file_align ( section_memsz );
  703. debug = xmalloc ( sizeof ( *debug ) + section_filesz );
  704. memset ( debug, 0, sizeof ( *debug ) + section_filesz );
  705. contents = ( void * ) debug->contents;
  706. /* Fill in section header details */
  707. strncpy ( ( char * ) debug->hdr.Name, ".debug",
  708. sizeof ( debug->hdr.Name ) );
  709. debug->hdr.Misc.VirtualSize = section_memsz;
  710. debug->hdr.VirtualAddress = pe_header->nt.OptionalHeader.SizeOfImage;
  711. debug->hdr.SizeOfRawData = section_filesz;
  712. debug->hdr.Characteristics = ( EFI_IMAGE_SCN_CNT_INITIALIZED_DATA |
  713. EFI_IMAGE_SCN_MEM_NOT_PAGED |
  714. EFI_IMAGE_SCN_MEM_READ );
  715. debug->fixup = fixup_debug_section;
  716. /* Create section contents */
  717. contents->debug.TimeDateStamp = 0x10d1a884;
  718. contents->debug.Type = EFI_IMAGE_DEBUG_TYPE_CODEVIEW;
  719. contents->debug.SizeOfData =
  720. ( sizeof ( *contents ) - sizeof ( contents->debug ) );
  721. contents->debug.RVA = ( debug->hdr.VirtualAddress +
  722. offsetof ( typeof ( *contents ), rsds ) );
  723. contents->debug.FileOffset = contents->debug.RVA;
  724. contents->rsds.Signature = CODEVIEW_SIGNATURE_RSDS;
  725. snprintf ( contents->name, sizeof ( contents->name ), "%s",
  726. filename );
  727. /* Update file header details */
  728. pe_header->nt.FileHeader.NumberOfSections++;
  729. pe_header->nt.OptionalHeader.SizeOfHeaders += sizeof ( debug->hdr );
  730. pe_header->nt.OptionalHeader.SizeOfImage += section_filesz;
  731. debugdir = &(pe_header->nt.OptionalHeader.DataDirectory
  732. [EFI_IMAGE_DIRECTORY_ENTRY_DEBUG]);
  733. debugdir->VirtualAddress = debug->hdr.VirtualAddress;
  734. debugdir->Size = sizeof ( contents->debug );
  735. return debug;
  736. }
  737. /**
  738. * Write out PE file
  739. *
  740. * @v pe_header PE file header
  741. * @v pe_sections List of PE sections
  742. * @v pe Output file
  743. */
  744. static void write_pe_file ( struct pe_header *pe_header,
  745. struct pe_section *pe_sections,
  746. FILE *pe ) {
  747. struct pe_section *section;
  748. unsigned long fpos = 0;
  749. /* Align length of headers */
  750. fpos = pe_header->nt.OptionalHeader.SizeOfHeaders =
  751. efi_file_align ( pe_header->nt.OptionalHeader.SizeOfHeaders );
  752. /* Assign raw data pointers */
  753. for ( section = pe_sections ; section ; section = section->next ) {
  754. if ( section->hdr.SizeOfRawData ) {
  755. section->hdr.PointerToRawData = fpos;
  756. fpos += section->hdr.SizeOfRawData;
  757. fpos = efi_file_align ( fpos );
  758. }
  759. if ( section->fixup )
  760. section->fixup ( section );
  761. }
  762. /* Write file header */
  763. if ( fwrite ( pe_header, sizeof ( *pe_header ), 1, pe ) != 1 ) {
  764. perror ( "Could not write PE header" );
  765. exit ( 1 );
  766. }
  767. /* Write section headers */
  768. for ( section = pe_sections ; section ; section = section->next ) {
  769. if ( fwrite ( &section->hdr, sizeof ( section->hdr ),
  770. 1, pe ) != 1 ) {
  771. perror ( "Could not write section header" );
  772. exit ( 1 );
  773. }
  774. }
  775. /* Write sections */
  776. for ( section = pe_sections ; section ; section = section->next ) {
  777. if ( fseek ( pe, section->hdr.PointerToRawData,
  778. SEEK_SET ) != 0 ) {
  779. eprintf ( "Could not seek to %x: %s\n",
  780. section->hdr.PointerToRawData,
  781. strerror ( errno ) );
  782. exit ( 1 );
  783. }
  784. if ( section->hdr.SizeOfRawData &&
  785. ( fwrite ( section->contents, section->hdr.SizeOfRawData,
  786. 1, pe ) != 1 ) ) {
  787. eprintf ( "Could not write section %.8s: %s\n",
  788. section->hdr.Name, strerror ( errno ) );
  789. exit ( 1 );
  790. }
  791. }
  792. }
  793. /**
  794. * Convert ELF to PE
  795. *
  796. * @v elf_name ELF file name
  797. * @v pe_name PE file name
  798. */
  799. static void elf2pe ( const char *elf_name, const char *pe_name,
  800. struct options *opts ) {
  801. char pe_name_tmp[ strlen ( pe_name ) + 1 ];
  802. struct pe_relocs *pe_reltab = NULL;
  803. struct pe_section *pe_sections = NULL;
  804. struct pe_section **next_pe_section = &pe_sections;
  805. struct pe_header pe_header;
  806. struct elf_file elf;
  807. const Elf_Shdr *shdr;
  808. size_t offset;
  809. unsigned int i;
  810. FILE *pe;
  811. /* Create a modifiable copy of the PE name */
  812. memcpy ( pe_name_tmp, pe_name, sizeof ( pe_name_tmp ) );
  813. /* Read ELF file */
  814. read_elf_file ( elf_name, &elf );
  815. /* Initialise the PE header */
  816. memcpy ( &pe_header, &efi_pe_header, sizeof ( pe_header ) );
  817. set_machine ( &elf, &pe_header );
  818. pe_header.nt.OptionalHeader.AddressOfEntryPoint = elf.ehdr->e_entry;
  819. pe_header.nt.OptionalHeader.Subsystem = opts->subsystem;
  820. /* Process input sections */
  821. for ( i = 0 ; i < elf.ehdr->e_shnum ; i++ ) {
  822. offset = ( elf.ehdr->e_shoff + ( i * elf.ehdr->e_shentsize ) );
  823. shdr = ( elf.data + offset );
  824. /* Process section */
  825. if ( shdr->sh_flags & SHF_ALLOC ) {
  826. /* Create output section */
  827. *(next_pe_section) = process_section ( &elf, shdr,
  828. &pe_header );
  829. next_pe_section = &(*next_pe_section)->next;
  830. } else if ( shdr->sh_type == SHT_REL ) {
  831. /* Process .rel relocations */
  832. process_relocs ( &elf, shdr, sizeof ( Elf_Rel ),
  833. &pe_reltab );
  834. } else if ( shdr->sh_type == SHT_RELA ) {
  835. /* Process .rela relocations */
  836. process_relocs ( &elf, shdr, sizeof ( Elf_Rela ),
  837. &pe_reltab );
  838. }
  839. }
  840. /* Create the .reloc section */
  841. *(next_pe_section) = create_reloc_section ( &pe_header, pe_reltab );
  842. next_pe_section = &(*next_pe_section)->next;
  843. /* Create the .debug section */
  844. *(next_pe_section) = create_debug_section ( &pe_header,
  845. basename ( pe_name_tmp ) );
  846. next_pe_section = &(*next_pe_section)->next;
  847. /* Write out PE file */
  848. pe = fopen ( pe_name, "w" );
  849. if ( ! pe ) {
  850. eprintf ( "Could not open %s for writing: %s\n",
  851. pe_name, strerror ( errno ) );
  852. exit ( 1 );
  853. }
  854. write_pe_file ( &pe_header, pe_sections, pe );
  855. fclose ( pe );
  856. /* Unmap ELF file */
  857. munmap ( elf.data, elf.len );
  858. }
  859. /**
  860. * Print help
  861. *
  862. * @v program_name Program name
  863. */
  864. static void print_help ( const char *program_name ) {
  865. eprintf ( "Syntax: %s [--subsystem=<number>] infile outfile\n",
  866. program_name );
  867. }
  868. /**
  869. * Parse command-line options
  870. *
  871. * @v argc Argument count
  872. * @v argv Argument list
  873. * @v opts Options structure to populate
  874. */
  875. static int parse_options ( const int argc, char **argv,
  876. struct options *opts ) {
  877. char *end;
  878. int c;
  879. while (1) {
  880. int option_index = 0;
  881. static struct option long_options[] = {
  882. { "subsystem", required_argument, NULL, 's' },
  883. { "help", 0, NULL, 'h' },
  884. { 0, 0, 0, 0 }
  885. };
  886. if ( ( c = getopt_long ( argc, argv, "s:h",
  887. long_options,
  888. &option_index ) ) == -1 ) {
  889. break;
  890. }
  891. switch ( c ) {
  892. case 's':
  893. opts->subsystem = strtoul ( optarg, &end, 0 );
  894. if ( *end ) {
  895. eprintf ( "Invalid subsytem \"%s\"\n",
  896. optarg );
  897. exit ( 2 );
  898. }
  899. break;
  900. case 'h':
  901. print_help ( argv[0] );
  902. exit ( 0 );
  903. case '?':
  904. default:
  905. exit ( 2 );
  906. }
  907. }
  908. return optind;
  909. }
  910. int main ( int argc, char **argv ) {
  911. struct options opts = {
  912. .subsystem = EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION,
  913. };
  914. int infile_index;
  915. const char *infile;
  916. const char *outfile;
  917. /* Parse command-line arguments */
  918. infile_index = parse_options ( argc, argv, &opts );
  919. if ( argc != ( infile_index + 2 ) ) {
  920. print_help ( argv[0] );
  921. exit ( 2 );
  922. }
  923. infile = argv[infile_index];
  924. outfile = argv[infile_index + 1];
  925. /* Convert file */
  926. elf2pe ( infile, outfile, &opts );
  927. return 0;
  928. }