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

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