Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

elf2efi.c 28KB

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