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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  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_THM_PC22 ) :
  578. case ELF_MREL ( EM_ARM, R_ARM_THM_JUMP24 ) :
  579. case ELF_MREL ( EM_ARM, R_ARM_V4BX ):
  580. case ELF_MREL ( EM_X86_64, R_X86_64_PC32 ) :
  581. case ELF_MREL ( EM_AARCH64, R_AARCH64_CALL26 ) :
  582. case ELF_MREL ( EM_AARCH64, R_AARCH64_JUMP26 ) :
  583. case ELF_MREL ( EM_AARCH64, R_AARCH64_ADR_PREL_LO21 ) :
  584. case ELF_MREL ( EM_AARCH64, R_AARCH64_ADR_PREL_PG_HI21 ) :
  585. case ELF_MREL ( EM_AARCH64, R_AARCH64_ADD_ABS_LO12_NC ) :
  586. case ELF_MREL ( EM_AARCH64, R_AARCH64_LDST8_ABS_LO12_NC ) :
  587. case ELF_MREL ( EM_AARCH64, R_AARCH64_LDST16_ABS_LO12_NC ) :
  588. case ELF_MREL ( EM_AARCH64, R_AARCH64_LDST32_ABS_LO12_NC ) :
  589. case ELF_MREL ( EM_AARCH64, R_AARCH64_LDST64_ABS_LO12_NC ) :
  590. /* Skip PC-relative relocations; all relative
  591. * offsets remain unaltered when the object is
  592. * loaded.
  593. */
  594. break;
  595. default:
  596. eprintf ( "Unrecognised relocation type %d\n", type );
  597. exit ( 1 );
  598. }
  599. }
  600. }
  601. /**
  602. * Process relocation records
  603. *
  604. * @v elf ELF file
  605. * @v shdr ELF section header
  606. * @v stride Relocation record size
  607. * @v pe_reltab PE relocation table to fill in
  608. */
  609. static void process_relocs ( struct elf_file *elf, const Elf_Shdr *shdr,
  610. size_t stride, struct pe_relocs **pe_reltab ) {
  611. const Elf_Shdr *symtab;
  612. const Elf_Sym *syms;
  613. const Elf_Rel *rel;
  614. unsigned int nsyms;
  615. unsigned int nrels;
  616. unsigned int i;
  617. /* Identify symbol table */
  618. symtab = ( elf->data + elf->ehdr->e_shoff +
  619. ( shdr->sh_link * elf->ehdr->e_shentsize ) );
  620. syms = ( elf->data + symtab->sh_offset );
  621. nsyms = ( symtab->sh_size / sizeof ( syms[0] ) );
  622. /* Process each relocation */
  623. rel = ( elf->data + shdr->sh_offset );
  624. nrels = ( shdr->sh_size / stride );
  625. for ( i = 0 ; i < nrels ; i++ ) {
  626. process_reloc ( elf, shdr, syms, nsyms, rel, pe_reltab );
  627. rel = ( ( ( const void * ) rel ) + stride );
  628. }
  629. }
  630. /**
  631. * Create relocations section
  632. *
  633. * @v pe_header PE file header
  634. * @v pe_reltab PE relocation table
  635. * @ret section Relocation section
  636. */
  637. static struct pe_section *
  638. create_reloc_section ( struct pe_header *pe_header,
  639. struct pe_relocs *pe_reltab ) {
  640. struct pe_section *reloc;
  641. size_t section_memsz;
  642. size_t section_filesz;
  643. EFI_IMAGE_DATA_DIRECTORY *relocdir;
  644. /* Allocate PE section */
  645. section_memsz = output_pe_reltab ( pe_reltab, NULL );
  646. section_filesz = efi_file_align ( section_memsz );
  647. reloc = xmalloc ( sizeof ( *reloc ) + section_filesz );
  648. memset ( reloc, 0, sizeof ( *reloc ) + section_filesz );
  649. /* Fill in section header details */
  650. strncpy ( ( char * ) reloc->hdr.Name, ".reloc",
  651. sizeof ( reloc->hdr.Name ) );
  652. reloc->hdr.Misc.VirtualSize = section_memsz;
  653. reloc->hdr.VirtualAddress = pe_header->nt.OptionalHeader.SizeOfImage;
  654. reloc->hdr.SizeOfRawData = section_filesz;
  655. reloc->hdr.Characteristics = ( EFI_IMAGE_SCN_CNT_INITIALIZED_DATA |
  656. EFI_IMAGE_SCN_MEM_NOT_PAGED |
  657. EFI_IMAGE_SCN_MEM_READ );
  658. /* Copy in section contents */
  659. output_pe_reltab ( pe_reltab, reloc->contents );
  660. /* Update file header details */
  661. pe_header->nt.FileHeader.NumberOfSections++;
  662. pe_header->nt.OptionalHeader.SizeOfHeaders += sizeof ( reloc->hdr );
  663. pe_header->nt.OptionalHeader.SizeOfImage += section_filesz;
  664. relocdir = &(pe_header->nt.OptionalHeader.DataDirectory
  665. [EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC]);
  666. relocdir->VirtualAddress = reloc->hdr.VirtualAddress;
  667. relocdir->Size = reloc->hdr.Misc.VirtualSize;
  668. return reloc;
  669. }
  670. /**
  671. * Fix up debug section
  672. *
  673. * @v debug Debug section
  674. */
  675. static void fixup_debug_section ( struct pe_section *debug ) {
  676. EFI_IMAGE_DEBUG_DIRECTORY_ENTRY *contents;
  677. /* Fix up FileOffset */
  678. contents = ( ( void * ) debug->contents );
  679. contents->FileOffset += ( debug->hdr.PointerToRawData -
  680. debug->hdr.VirtualAddress );
  681. }
  682. /**
  683. * Create debug section
  684. *
  685. * @v pe_header PE file header
  686. * @ret section Debug section
  687. */
  688. static struct pe_section *
  689. create_debug_section ( struct pe_header *pe_header, const char *filename ) {
  690. struct pe_section *debug;
  691. size_t section_memsz;
  692. size_t section_filesz;
  693. EFI_IMAGE_DATA_DIRECTORY *debugdir;
  694. struct {
  695. EFI_IMAGE_DEBUG_DIRECTORY_ENTRY debug;
  696. EFI_IMAGE_DEBUG_CODEVIEW_RSDS_ENTRY rsds;
  697. char name[ strlen ( filename ) + 1 ];
  698. } *contents;
  699. /* Allocate PE section */
  700. section_memsz = sizeof ( *contents );
  701. section_filesz = efi_file_align ( section_memsz );
  702. debug = xmalloc ( sizeof ( *debug ) + section_filesz );
  703. memset ( debug, 0, sizeof ( *debug ) + section_filesz );
  704. contents = ( void * ) debug->contents;
  705. /* Fill in section header details */
  706. strncpy ( ( char * ) debug->hdr.Name, ".debug",
  707. sizeof ( debug->hdr.Name ) );
  708. debug->hdr.Misc.VirtualSize = section_memsz;
  709. debug->hdr.VirtualAddress = pe_header->nt.OptionalHeader.SizeOfImage;
  710. debug->hdr.SizeOfRawData = section_filesz;
  711. debug->hdr.Characteristics = ( EFI_IMAGE_SCN_CNT_INITIALIZED_DATA |
  712. EFI_IMAGE_SCN_MEM_NOT_PAGED |
  713. EFI_IMAGE_SCN_MEM_READ );
  714. debug->fixup = fixup_debug_section;
  715. /* Create section contents */
  716. contents->debug.TimeDateStamp = 0x10d1a884;
  717. contents->debug.Type = EFI_IMAGE_DEBUG_TYPE_CODEVIEW;
  718. contents->debug.SizeOfData =
  719. ( sizeof ( *contents ) - sizeof ( contents->debug ) );
  720. contents->debug.RVA = ( debug->hdr.VirtualAddress +
  721. offsetof ( typeof ( *contents ), rsds ) );
  722. contents->debug.FileOffset = contents->debug.RVA;
  723. contents->rsds.Signature = CODEVIEW_SIGNATURE_RSDS;
  724. snprintf ( contents->name, sizeof ( contents->name ), "%s",
  725. filename );
  726. /* Update file header details */
  727. pe_header->nt.FileHeader.NumberOfSections++;
  728. pe_header->nt.OptionalHeader.SizeOfHeaders += sizeof ( debug->hdr );
  729. pe_header->nt.OptionalHeader.SizeOfImage += section_filesz;
  730. debugdir = &(pe_header->nt.OptionalHeader.DataDirectory
  731. [EFI_IMAGE_DIRECTORY_ENTRY_DEBUG]);
  732. debugdir->VirtualAddress = debug->hdr.VirtualAddress;
  733. debugdir->Size = sizeof ( contents->debug );
  734. return debug;
  735. }
  736. /**
  737. * Write out PE file
  738. *
  739. * @v pe_header PE file header
  740. * @v pe_sections List of PE sections
  741. * @v pe Output file
  742. */
  743. static void write_pe_file ( struct pe_header *pe_header,
  744. struct pe_section *pe_sections,
  745. FILE *pe ) {
  746. struct pe_section *section;
  747. unsigned long fpos = 0;
  748. /* Align length of headers */
  749. fpos = pe_header->nt.OptionalHeader.SizeOfHeaders =
  750. efi_file_align ( pe_header->nt.OptionalHeader.SizeOfHeaders );
  751. /* Assign raw data pointers */
  752. for ( section = pe_sections ; section ; section = section->next ) {
  753. if ( section->hdr.SizeOfRawData ) {
  754. section->hdr.PointerToRawData = fpos;
  755. fpos += section->hdr.SizeOfRawData;
  756. fpos = efi_file_align ( fpos );
  757. }
  758. if ( section->fixup )
  759. section->fixup ( section );
  760. }
  761. /* Write file header */
  762. if ( fwrite ( pe_header, sizeof ( *pe_header ), 1, pe ) != 1 ) {
  763. perror ( "Could not write PE header" );
  764. exit ( 1 );
  765. }
  766. /* Write section headers */
  767. for ( section = pe_sections ; section ; section = section->next ) {
  768. if ( fwrite ( &section->hdr, sizeof ( section->hdr ),
  769. 1, pe ) != 1 ) {
  770. perror ( "Could not write section header" );
  771. exit ( 1 );
  772. }
  773. }
  774. /* Write sections */
  775. for ( section = pe_sections ; section ; section = section->next ) {
  776. if ( fseek ( pe, section->hdr.PointerToRawData,
  777. SEEK_SET ) != 0 ) {
  778. eprintf ( "Could not seek to %x: %s\n",
  779. section->hdr.PointerToRawData,
  780. strerror ( errno ) );
  781. exit ( 1 );
  782. }
  783. if ( section->hdr.SizeOfRawData &&
  784. ( fwrite ( section->contents, section->hdr.SizeOfRawData,
  785. 1, pe ) != 1 ) ) {
  786. eprintf ( "Could not write section %.8s: %s\n",
  787. section->hdr.Name, strerror ( errno ) );
  788. exit ( 1 );
  789. }
  790. }
  791. }
  792. /**
  793. * Convert ELF to PE
  794. *
  795. * @v elf_name ELF file name
  796. * @v pe_name PE file name
  797. */
  798. static void elf2pe ( const char *elf_name, const char *pe_name,
  799. struct options *opts ) {
  800. char pe_name_tmp[ strlen ( pe_name ) + 1 ];
  801. struct pe_relocs *pe_reltab = NULL;
  802. struct pe_section *pe_sections = NULL;
  803. struct pe_section **next_pe_section = &pe_sections;
  804. struct pe_header pe_header;
  805. struct elf_file elf;
  806. const Elf_Shdr *shdr;
  807. size_t offset;
  808. unsigned int i;
  809. FILE *pe;
  810. /* Create a modifiable copy of the PE name */
  811. memcpy ( pe_name_tmp, pe_name, sizeof ( pe_name_tmp ) );
  812. /* Read ELF file */
  813. read_elf_file ( elf_name, &elf );
  814. /* Initialise the PE header */
  815. memcpy ( &pe_header, &efi_pe_header, sizeof ( pe_header ) );
  816. set_machine ( &elf, &pe_header );
  817. pe_header.nt.OptionalHeader.AddressOfEntryPoint = elf.ehdr->e_entry;
  818. pe_header.nt.OptionalHeader.Subsystem = opts->subsystem;
  819. /* Process input sections */
  820. for ( i = 0 ; i < elf.ehdr->e_shnum ; i++ ) {
  821. offset = ( elf.ehdr->e_shoff + ( i * elf.ehdr->e_shentsize ) );
  822. shdr = ( elf.data + offset );
  823. /* Process section */
  824. if ( shdr->sh_flags & SHF_ALLOC ) {
  825. /* Create output section */
  826. *(next_pe_section) = process_section ( &elf, shdr,
  827. &pe_header );
  828. next_pe_section = &(*next_pe_section)->next;
  829. } else if ( shdr->sh_type == SHT_REL ) {
  830. /* Process .rel relocations */
  831. process_relocs ( &elf, shdr, sizeof ( Elf_Rel ),
  832. &pe_reltab );
  833. } else if ( shdr->sh_type == SHT_RELA ) {
  834. /* Process .rela relocations */
  835. process_relocs ( &elf, shdr, sizeof ( Elf_Rela ),
  836. &pe_reltab );
  837. }
  838. }
  839. /* Create the .reloc section */
  840. *(next_pe_section) = create_reloc_section ( &pe_header, pe_reltab );
  841. next_pe_section = &(*next_pe_section)->next;
  842. /* Create the .debug section */
  843. *(next_pe_section) = create_debug_section ( &pe_header,
  844. basename ( pe_name_tmp ) );
  845. next_pe_section = &(*next_pe_section)->next;
  846. /* Write out PE file */
  847. pe = fopen ( pe_name, "w" );
  848. if ( ! pe ) {
  849. eprintf ( "Could not open %s for writing: %s\n",
  850. pe_name, strerror ( errno ) );
  851. exit ( 1 );
  852. }
  853. write_pe_file ( &pe_header, pe_sections, pe );
  854. fclose ( pe );
  855. /* Unmap ELF file */
  856. munmap ( elf.data, elf.len );
  857. }
  858. /**
  859. * Print help
  860. *
  861. * @v program_name Program name
  862. */
  863. static void print_help ( const char *program_name ) {
  864. eprintf ( "Syntax: %s [--subsystem=<number>] infile outfile\n",
  865. program_name );
  866. }
  867. /**
  868. * Parse command-line options
  869. *
  870. * @v argc Argument count
  871. * @v argv Argument list
  872. * @v opts Options structure to populate
  873. */
  874. static int parse_options ( const int argc, char **argv,
  875. struct options *opts ) {
  876. char *end;
  877. int c;
  878. while (1) {
  879. int option_index = 0;
  880. static struct option long_options[] = {
  881. { "subsystem", required_argument, NULL, 's' },
  882. { "help", 0, NULL, 'h' },
  883. { 0, 0, 0, 0 }
  884. };
  885. if ( ( c = getopt_long ( argc, argv, "s:h",
  886. long_options,
  887. &option_index ) ) == -1 ) {
  888. break;
  889. }
  890. switch ( c ) {
  891. case 's':
  892. opts->subsystem = strtoul ( optarg, &end, 0 );
  893. if ( *end ) {
  894. eprintf ( "Invalid subsytem \"%s\"\n",
  895. optarg );
  896. exit ( 2 );
  897. }
  898. break;
  899. case 'h':
  900. print_help ( argv[0] );
  901. exit ( 0 );
  902. case '?':
  903. default:
  904. exit ( 2 );
  905. }
  906. }
  907. return optind;
  908. }
  909. int main ( int argc, char **argv ) {
  910. struct options opts = {
  911. .subsystem = EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION,
  912. };
  913. int infile_index;
  914. const char *infile;
  915. const char *outfile;
  916. /* Parse command-line arguments */
  917. infile_index = parse_options ( argc, argv, &opts );
  918. if ( argc != ( infile_index + 2 ) ) {
  919. print_help ( argv[0] );
  920. exit ( 2 );
  921. }
  922. infile = argv[infile_index];
  923. outfile = argv[infile_index + 1];
  924. /* Convert file */
  925. elf2pe ( infile, outfile, &opts );
  926. return 0;
  927. }