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

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