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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  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 name_len;
  417. size_t section_memsz;
  418. size_t section_filesz;
  419. unsigned long code_start;
  420. unsigned long code_end;
  421. unsigned long data_start;
  422. unsigned long data_mid;
  423. unsigned long data_end;
  424. unsigned long start;
  425. unsigned long end;
  426. unsigned long *applicable_start;
  427. unsigned long *applicable_end;
  428. /* Get section name */
  429. name = elf_string ( elf, elf->ehdr->e_shstrndx, shdr->sh_name );
  430. /* Extract current RVA limits from file header */
  431. code_start = pe_header->nt.OptionalHeader.BaseOfCode;
  432. code_end = ( code_start + pe_header->nt.OptionalHeader.SizeOfCode );
  433. #if defined(EFI_TARGET32)
  434. data_start = pe_header->nt.OptionalHeader.BaseOfData;
  435. #elif defined(EFI_TARGET64)
  436. data_start = code_end;
  437. #endif
  438. data_mid = ( data_start +
  439. pe_header->nt.OptionalHeader.SizeOfInitializedData );
  440. data_end = ( data_mid +
  441. pe_header->nt.OptionalHeader.SizeOfUninitializedData );
  442. /* Allocate PE section */
  443. section_memsz = shdr->sh_size;
  444. section_filesz = ( ( shdr->sh_type == SHT_PROGBITS ) ?
  445. efi_file_align ( section_memsz ) : 0 );
  446. new = xmalloc ( sizeof ( *new ) + section_filesz );
  447. memset ( new, 0, sizeof ( *new ) + section_filesz );
  448. /* Fill in section header details */
  449. name_len = strlen ( name );
  450. if ( name_len > sizeof ( new->hdr.Name ) )
  451. name_len = sizeof ( new->hdr.Name );
  452. memcpy ( new->hdr.Name, name, name_len );
  453. new->hdr.Misc.VirtualSize = section_memsz;
  454. new->hdr.VirtualAddress = shdr->sh_addr;
  455. new->hdr.SizeOfRawData = section_filesz;
  456. /* Fill in section characteristics and update RVA limits */
  457. if ( ( shdr->sh_type == SHT_PROGBITS ) &&
  458. ( shdr->sh_flags & SHF_EXECINSTR ) ) {
  459. /* .text-type section */
  460. new->hdr.Characteristics =
  461. ( EFI_IMAGE_SCN_CNT_CODE |
  462. EFI_IMAGE_SCN_MEM_NOT_PAGED |
  463. EFI_IMAGE_SCN_MEM_EXECUTE |
  464. EFI_IMAGE_SCN_MEM_READ );
  465. applicable_start = &code_start;
  466. applicable_end = &code_end;
  467. } else if ( ( shdr->sh_type == SHT_PROGBITS ) &&
  468. ( shdr->sh_flags & SHF_WRITE ) ) {
  469. /* .data-type section */
  470. new->hdr.Characteristics =
  471. ( EFI_IMAGE_SCN_CNT_INITIALIZED_DATA |
  472. EFI_IMAGE_SCN_MEM_NOT_PAGED |
  473. EFI_IMAGE_SCN_MEM_READ |
  474. EFI_IMAGE_SCN_MEM_WRITE );
  475. applicable_start = &data_start;
  476. applicable_end = &data_mid;
  477. } else if ( shdr->sh_type == SHT_PROGBITS ) {
  478. /* .rodata-type section */
  479. new->hdr.Characteristics =
  480. ( EFI_IMAGE_SCN_CNT_INITIALIZED_DATA |
  481. EFI_IMAGE_SCN_MEM_NOT_PAGED |
  482. EFI_IMAGE_SCN_MEM_READ );
  483. applicable_start = &data_start;
  484. applicable_end = &data_mid;
  485. } else if ( shdr->sh_type == SHT_NOBITS ) {
  486. /* .bss-type section */
  487. new->hdr.Characteristics =
  488. ( EFI_IMAGE_SCN_CNT_UNINITIALIZED_DATA |
  489. EFI_IMAGE_SCN_MEM_NOT_PAGED |
  490. EFI_IMAGE_SCN_MEM_READ |
  491. EFI_IMAGE_SCN_MEM_WRITE );
  492. applicable_start = &data_mid;
  493. applicable_end = &data_end;
  494. } else {
  495. eprintf ( "Unrecognised characteristics for section %s\n",
  496. name );
  497. exit ( 1 );
  498. }
  499. /* Copy in section contents */
  500. if ( shdr->sh_type == SHT_PROGBITS ) {
  501. memcpy ( new->contents, ( elf->data + shdr->sh_offset ),
  502. shdr->sh_size );
  503. }
  504. /* Update RVA limits */
  505. start = new->hdr.VirtualAddress;
  506. end = ( start + new->hdr.Misc.VirtualSize );
  507. if ( ( ! *applicable_start ) || ( *applicable_start >= start ) )
  508. *applicable_start = start;
  509. if ( *applicable_end < end )
  510. *applicable_end = end;
  511. if ( data_start < code_end )
  512. data_start = code_end;
  513. if ( data_mid < data_start )
  514. data_mid = data_start;
  515. if ( data_end < data_mid )
  516. data_end = data_mid;
  517. /* Write RVA limits back to file header */
  518. pe_header->nt.OptionalHeader.BaseOfCode = code_start;
  519. pe_header->nt.OptionalHeader.SizeOfCode = ( code_end - code_start );
  520. #if defined(EFI_TARGET32)
  521. pe_header->nt.OptionalHeader.BaseOfData = data_start;
  522. #endif
  523. pe_header->nt.OptionalHeader.SizeOfInitializedData =
  524. ( data_mid - data_start );
  525. pe_header->nt.OptionalHeader.SizeOfUninitializedData =
  526. ( data_end - data_mid );
  527. /* Update remaining file header fields */
  528. pe_header->nt.FileHeader.NumberOfSections++;
  529. pe_header->nt.OptionalHeader.SizeOfHeaders += sizeof ( new->hdr );
  530. pe_header->nt.OptionalHeader.SizeOfImage =
  531. efi_file_align ( data_end );
  532. return new;
  533. }
  534. /**
  535. * Process relocation record
  536. *
  537. * @v elf ELF file
  538. * @v shdr ELF section header
  539. * @v syms Symbol table
  540. * @v nsyms Number of symbol table entries
  541. * @v rel Relocation record
  542. * @v pe_reltab PE relocation table to fill in
  543. */
  544. static void process_reloc ( struct elf_file *elf, const Elf_Shdr *shdr,
  545. const Elf_Sym *syms, unsigned int nsyms,
  546. const Elf_Rel *rel, struct pe_relocs **pe_reltab ) {
  547. unsigned int type = ELF_R_TYPE ( rel->r_info );
  548. unsigned int sym = ELF_R_SYM ( rel->r_info );
  549. unsigned int mrel = ELF_MREL ( elf->ehdr->e_machine, type );
  550. size_t offset = ( shdr->sh_addr + rel->r_offset );
  551. /* Look up symbol and process relocation */
  552. if ( sym >= nsyms ) {
  553. eprintf ( "Symbol out of range\n" );
  554. exit ( 1 );
  555. }
  556. if ( syms[sym].st_shndx == SHN_ABS ) {
  557. /* Skip absolute symbols; the symbol value won't
  558. * change when the object is loaded.
  559. */
  560. } else {
  561. switch ( mrel ) {
  562. case ELF_MREL ( EM_386, R_386_NONE ) :
  563. case ELF_MREL ( EM_ARM, R_ARM_NONE ) :
  564. case ELF_MREL ( EM_X86_64, R_X86_64_NONE ) :
  565. case ELF_MREL ( EM_AARCH64, R_AARCH64_NONE ) :
  566. case ELF_MREL ( EM_AARCH64, R_AARCH64_NULL ) :
  567. /* Ignore dummy relocations used by REQUIRE_SYMBOL() */
  568. break;
  569. case ELF_MREL ( EM_386, R_386_32 ) :
  570. case ELF_MREL ( EM_ARM, R_ARM_ABS32 ) :
  571. /* Generate a 4-byte PE relocation */
  572. generate_pe_reloc ( pe_reltab, offset, 4 );
  573. break;
  574. case ELF_MREL ( EM_X86_64, R_X86_64_64 ) :
  575. case ELF_MREL ( EM_AARCH64, R_AARCH64_ABS64 ) :
  576. /* Generate an 8-byte PE relocation */
  577. generate_pe_reloc ( pe_reltab, offset, 8 );
  578. break;
  579. case ELF_MREL ( EM_386, R_386_PC32 ) :
  580. case ELF_MREL ( EM_ARM, R_ARM_CALL ) :
  581. case ELF_MREL ( EM_ARM, R_ARM_REL32 ) :
  582. case ELF_MREL ( EM_ARM, R_ARM_THM_PC22 ) :
  583. case ELF_MREL ( EM_ARM, R_ARM_THM_JUMP24 ) :
  584. case ELF_MREL ( EM_ARM, R_ARM_V4BX ):
  585. case ELF_MREL ( EM_X86_64, R_X86_64_PC32 ) :
  586. case ELF_MREL ( EM_X86_64, R_X86_64_PLT32 ) :
  587. case ELF_MREL ( EM_AARCH64, R_AARCH64_CALL26 ) :
  588. case ELF_MREL ( EM_AARCH64, R_AARCH64_JUMP26 ) :
  589. case ELF_MREL ( EM_AARCH64, R_AARCH64_ADR_PREL_LO21 ) :
  590. case ELF_MREL ( EM_AARCH64, R_AARCH64_ADR_PREL_PG_HI21 ) :
  591. case ELF_MREL ( EM_AARCH64, R_AARCH64_ADD_ABS_LO12_NC ) :
  592. case ELF_MREL ( EM_AARCH64, R_AARCH64_LDST8_ABS_LO12_NC ) :
  593. case ELF_MREL ( EM_AARCH64, R_AARCH64_LDST16_ABS_LO12_NC ) :
  594. case ELF_MREL ( EM_AARCH64, R_AARCH64_LDST32_ABS_LO12_NC ) :
  595. case ELF_MREL ( EM_AARCH64, R_AARCH64_LDST64_ABS_LO12_NC ) :
  596. /* Skip PC-relative relocations; all relative
  597. * offsets remain unaltered when the object is
  598. * loaded.
  599. */
  600. break;
  601. default:
  602. eprintf ( "Unrecognised relocation type %d\n", type );
  603. exit ( 1 );
  604. }
  605. }
  606. }
  607. /**
  608. * Process relocation records
  609. *
  610. * @v elf ELF file
  611. * @v shdr ELF section header
  612. * @v stride Relocation record size
  613. * @v pe_reltab PE relocation table to fill in
  614. */
  615. static void process_relocs ( struct elf_file *elf, const Elf_Shdr *shdr,
  616. size_t stride, struct pe_relocs **pe_reltab ) {
  617. const Elf_Shdr *symtab;
  618. const Elf_Sym *syms;
  619. const Elf_Rel *rel;
  620. unsigned int nsyms;
  621. unsigned int nrels;
  622. unsigned int i;
  623. /* Identify symbol table */
  624. symtab = ( elf->data + elf->ehdr->e_shoff +
  625. ( shdr->sh_link * elf->ehdr->e_shentsize ) );
  626. syms = ( elf->data + symtab->sh_offset );
  627. nsyms = ( symtab->sh_size / sizeof ( syms[0] ) );
  628. /* Process each relocation */
  629. rel = ( elf->data + shdr->sh_offset );
  630. nrels = ( shdr->sh_size / stride );
  631. for ( i = 0 ; i < nrels ; i++ ) {
  632. process_reloc ( elf, shdr, syms, nsyms, rel, pe_reltab );
  633. rel = ( ( ( const void * ) rel ) + stride );
  634. }
  635. }
  636. /**
  637. * Create relocations section
  638. *
  639. * @v pe_header PE file header
  640. * @v pe_reltab PE relocation table
  641. * @ret section Relocation section
  642. */
  643. static struct pe_section *
  644. create_reloc_section ( struct pe_header *pe_header,
  645. struct pe_relocs *pe_reltab ) {
  646. struct pe_section *reloc;
  647. size_t section_memsz;
  648. size_t section_filesz;
  649. EFI_IMAGE_DATA_DIRECTORY *relocdir;
  650. /* Allocate PE section */
  651. section_memsz = output_pe_reltab ( pe_reltab, NULL );
  652. section_filesz = efi_file_align ( section_memsz );
  653. reloc = xmalloc ( sizeof ( *reloc ) + section_filesz );
  654. memset ( reloc, 0, sizeof ( *reloc ) + section_filesz );
  655. /* Fill in section header details */
  656. strncpy ( ( char * ) reloc->hdr.Name, ".reloc",
  657. sizeof ( reloc->hdr.Name ) );
  658. reloc->hdr.Misc.VirtualSize = section_memsz;
  659. reloc->hdr.VirtualAddress = pe_header->nt.OptionalHeader.SizeOfImage;
  660. reloc->hdr.SizeOfRawData = section_filesz;
  661. reloc->hdr.Characteristics = ( EFI_IMAGE_SCN_CNT_INITIALIZED_DATA |
  662. EFI_IMAGE_SCN_MEM_NOT_PAGED |
  663. EFI_IMAGE_SCN_MEM_READ );
  664. /* Copy in section contents */
  665. output_pe_reltab ( pe_reltab, reloc->contents );
  666. /* Update file header details */
  667. pe_header->nt.FileHeader.NumberOfSections++;
  668. pe_header->nt.OptionalHeader.SizeOfHeaders += sizeof ( reloc->hdr );
  669. pe_header->nt.OptionalHeader.SizeOfImage += section_filesz;
  670. relocdir = &(pe_header->nt.OptionalHeader.DataDirectory
  671. [EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC]);
  672. relocdir->VirtualAddress = reloc->hdr.VirtualAddress;
  673. relocdir->Size = reloc->hdr.Misc.VirtualSize;
  674. return reloc;
  675. }
  676. /**
  677. * Fix up debug section
  678. *
  679. * @v debug Debug section
  680. */
  681. static void fixup_debug_section ( struct pe_section *debug ) {
  682. EFI_IMAGE_DEBUG_DIRECTORY_ENTRY *contents;
  683. /* Fix up FileOffset */
  684. contents = ( ( void * ) debug->contents );
  685. contents->FileOffset += ( debug->hdr.PointerToRawData -
  686. debug->hdr.VirtualAddress );
  687. }
  688. /**
  689. * Create debug section
  690. *
  691. * @v pe_header PE file header
  692. * @ret section Debug section
  693. */
  694. static struct pe_section *
  695. create_debug_section ( struct pe_header *pe_header, const char *filename ) {
  696. struct pe_section *debug;
  697. size_t section_memsz;
  698. size_t section_filesz;
  699. EFI_IMAGE_DATA_DIRECTORY *debugdir;
  700. struct {
  701. EFI_IMAGE_DEBUG_DIRECTORY_ENTRY debug;
  702. EFI_IMAGE_DEBUG_CODEVIEW_RSDS_ENTRY rsds;
  703. char name[ strlen ( filename ) + 1 ];
  704. } *contents;
  705. /* Allocate PE section */
  706. section_memsz = sizeof ( *contents );
  707. section_filesz = efi_file_align ( section_memsz );
  708. debug = xmalloc ( sizeof ( *debug ) + section_filesz );
  709. memset ( debug, 0, sizeof ( *debug ) + section_filesz );
  710. contents = ( void * ) debug->contents;
  711. /* Fill in section header details */
  712. strncpy ( ( char * ) debug->hdr.Name, ".debug",
  713. sizeof ( debug->hdr.Name ) );
  714. debug->hdr.Misc.VirtualSize = section_memsz;
  715. debug->hdr.VirtualAddress = pe_header->nt.OptionalHeader.SizeOfImage;
  716. debug->hdr.SizeOfRawData = section_filesz;
  717. debug->hdr.Characteristics = ( EFI_IMAGE_SCN_CNT_INITIALIZED_DATA |
  718. EFI_IMAGE_SCN_MEM_NOT_PAGED |
  719. EFI_IMAGE_SCN_MEM_READ );
  720. debug->fixup = fixup_debug_section;
  721. /* Create section contents */
  722. contents->debug.TimeDateStamp = 0x10d1a884;
  723. contents->debug.Type = EFI_IMAGE_DEBUG_TYPE_CODEVIEW;
  724. contents->debug.SizeOfData =
  725. ( sizeof ( *contents ) - sizeof ( contents->debug ) );
  726. contents->debug.RVA = ( debug->hdr.VirtualAddress +
  727. offsetof ( typeof ( *contents ), rsds ) );
  728. contents->debug.FileOffset = contents->debug.RVA;
  729. contents->rsds.Signature = CODEVIEW_SIGNATURE_RSDS;
  730. snprintf ( contents->name, sizeof ( contents->name ), "%s",
  731. filename );
  732. /* Update file header details */
  733. pe_header->nt.FileHeader.NumberOfSections++;
  734. pe_header->nt.OptionalHeader.SizeOfHeaders += sizeof ( debug->hdr );
  735. pe_header->nt.OptionalHeader.SizeOfImage += section_filesz;
  736. debugdir = &(pe_header->nt.OptionalHeader.DataDirectory
  737. [EFI_IMAGE_DIRECTORY_ENTRY_DEBUG]);
  738. debugdir->VirtualAddress = debug->hdr.VirtualAddress;
  739. debugdir->Size = sizeof ( contents->debug );
  740. return debug;
  741. }
  742. /**
  743. * Write out PE file
  744. *
  745. * @v pe_header PE file header
  746. * @v pe_sections List of PE sections
  747. * @v pe Output file
  748. */
  749. static void write_pe_file ( struct pe_header *pe_header,
  750. struct pe_section *pe_sections,
  751. FILE *pe ) {
  752. struct pe_section *section;
  753. unsigned long fpos = 0;
  754. /* Align length of headers */
  755. fpos = pe_header->nt.OptionalHeader.SizeOfHeaders =
  756. efi_file_align ( pe_header->nt.OptionalHeader.SizeOfHeaders );
  757. /* Assign raw data pointers */
  758. for ( section = pe_sections ; section ; section = section->next ) {
  759. if ( section->hdr.SizeOfRawData ) {
  760. section->hdr.PointerToRawData = fpos;
  761. fpos += section->hdr.SizeOfRawData;
  762. fpos = efi_file_align ( fpos );
  763. }
  764. if ( section->fixup )
  765. section->fixup ( section );
  766. }
  767. /* Write file header */
  768. if ( fwrite ( pe_header, sizeof ( *pe_header ), 1, pe ) != 1 ) {
  769. perror ( "Could not write PE header" );
  770. exit ( 1 );
  771. }
  772. /* Write section headers */
  773. for ( section = pe_sections ; section ; section = section->next ) {
  774. if ( fwrite ( &section->hdr, sizeof ( section->hdr ),
  775. 1, pe ) != 1 ) {
  776. perror ( "Could not write section header" );
  777. exit ( 1 );
  778. }
  779. }
  780. /* Write sections */
  781. for ( section = pe_sections ; section ; section = section->next ) {
  782. if ( fseek ( pe, section->hdr.PointerToRawData,
  783. SEEK_SET ) != 0 ) {
  784. eprintf ( "Could not seek to %x: %s\n",
  785. section->hdr.PointerToRawData,
  786. strerror ( errno ) );
  787. exit ( 1 );
  788. }
  789. if ( section->hdr.SizeOfRawData &&
  790. ( fwrite ( section->contents, section->hdr.SizeOfRawData,
  791. 1, pe ) != 1 ) ) {
  792. eprintf ( "Could not write section %.8s: %s\n",
  793. section->hdr.Name, strerror ( errno ) );
  794. exit ( 1 );
  795. }
  796. }
  797. }
  798. /**
  799. * Convert ELF to PE
  800. *
  801. * @v elf_name ELF file name
  802. * @v pe_name PE file name
  803. */
  804. static void elf2pe ( const char *elf_name, const char *pe_name,
  805. struct options *opts ) {
  806. char pe_name_tmp[ strlen ( pe_name ) + 1 ];
  807. struct pe_relocs *pe_reltab = NULL;
  808. struct pe_section *pe_sections = NULL;
  809. struct pe_section **next_pe_section = &pe_sections;
  810. struct pe_header pe_header;
  811. struct elf_file elf;
  812. const Elf_Shdr *shdr;
  813. size_t offset;
  814. unsigned int i;
  815. FILE *pe;
  816. /* Create a modifiable copy of the PE name */
  817. memcpy ( pe_name_tmp, pe_name, sizeof ( pe_name_tmp ) );
  818. /* Read ELF file */
  819. read_elf_file ( elf_name, &elf );
  820. /* Initialise the PE header */
  821. memcpy ( &pe_header, &efi_pe_header, sizeof ( pe_header ) );
  822. set_machine ( &elf, &pe_header );
  823. pe_header.nt.OptionalHeader.AddressOfEntryPoint = elf.ehdr->e_entry;
  824. pe_header.nt.OptionalHeader.Subsystem = opts->subsystem;
  825. /* Process input sections */
  826. for ( i = 0 ; i < elf.ehdr->e_shnum ; i++ ) {
  827. offset = ( elf.ehdr->e_shoff + ( i * elf.ehdr->e_shentsize ) );
  828. shdr = ( elf.data + offset );
  829. /* Process section */
  830. if ( shdr->sh_flags & SHF_ALLOC ) {
  831. /* Create output section */
  832. *(next_pe_section) = process_section ( &elf, shdr,
  833. &pe_header );
  834. next_pe_section = &(*next_pe_section)->next;
  835. } else if ( shdr->sh_type == SHT_REL ) {
  836. /* Process .rel relocations */
  837. process_relocs ( &elf, shdr, sizeof ( Elf_Rel ),
  838. &pe_reltab );
  839. } else if ( shdr->sh_type == SHT_RELA ) {
  840. /* Process .rela relocations */
  841. process_relocs ( &elf, shdr, sizeof ( Elf_Rela ),
  842. &pe_reltab );
  843. }
  844. }
  845. /* Create the .reloc section */
  846. *(next_pe_section) = create_reloc_section ( &pe_header, pe_reltab );
  847. next_pe_section = &(*next_pe_section)->next;
  848. /* Create the .debug section */
  849. *(next_pe_section) = create_debug_section ( &pe_header,
  850. basename ( pe_name_tmp ) );
  851. next_pe_section = &(*next_pe_section)->next;
  852. /* Write out PE file */
  853. pe = fopen ( pe_name, "w" );
  854. if ( ! pe ) {
  855. eprintf ( "Could not open %s for writing: %s\n",
  856. pe_name, strerror ( errno ) );
  857. exit ( 1 );
  858. }
  859. write_pe_file ( &pe_header, pe_sections, pe );
  860. fclose ( pe );
  861. /* Unmap ELF file */
  862. munmap ( elf.data, elf.len );
  863. }
  864. /**
  865. * Print help
  866. *
  867. * @v program_name Program name
  868. */
  869. static void print_help ( const char *program_name ) {
  870. eprintf ( "Syntax: %s [--subsystem=<number>] infile outfile\n",
  871. program_name );
  872. }
  873. /**
  874. * Parse command-line options
  875. *
  876. * @v argc Argument count
  877. * @v argv Argument list
  878. * @v opts Options structure to populate
  879. */
  880. static int parse_options ( const int argc, char **argv,
  881. struct options *opts ) {
  882. char *end;
  883. int c;
  884. while (1) {
  885. int option_index = 0;
  886. static struct option long_options[] = {
  887. { "subsystem", required_argument, NULL, 's' },
  888. { "help", 0, NULL, 'h' },
  889. { 0, 0, 0, 0 }
  890. };
  891. if ( ( c = getopt_long ( argc, argv, "s:h",
  892. long_options,
  893. &option_index ) ) == -1 ) {
  894. break;
  895. }
  896. switch ( c ) {
  897. case 's':
  898. opts->subsystem = strtoul ( optarg, &end, 0 );
  899. if ( *end ) {
  900. eprintf ( "Invalid subsytem \"%s\"\n",
  901. optarg );
  902. exit ( 2 );
  903. }
  904. break;
  905. case 'h':
  906. print_help ( argv[0] );
  907. exit ( 0 );
  908. case '?':
  909. default:
  910. exit ( 2 );
  911. }
  912. }
  913. return optind;
  914. }
  915. int main ( int argc, char **argv ) {
  916. struct options opts = {
  917. .subsystem = EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION,
  918. };
  919. int infile_index;
  920. const char *infile;
  921. const char *outfile;
  922. /* Parse command-line arguments */
  923. infile_index = parse_options ( argc, argv, &opts );
  924. if ( argc != ( infile_index + 2 ) ) {
  925. print_help ( argv[0] );
  926. exit ( 2 );
  927. }
  928. infile = argv[infile_index];
  929. outfile = argv[infile_index + 1];
  930. /* Convert file */
  931. elf2pe ( infile, outfile, &opts );
  932. return 0;
  933. }