1 /* Copyright (C) 2002 Red Hat, Inc. 2 Written by Ulrich Drepper <drepper (at) redhat.com>, 2002. 3 4 This program is Open Source software; you can redistribute it and/or 5 modify it under the terms of the Open Software License version 1.0 as 6 published by the Open Source Initiative. 7 8 You should have received a copy of the Open Software License along 9 with this program; if not, you may obtain a copy of the Open Software 10 License version 1.0 from http://www.opensource.org/licenses/osl.php or 11 by writing the Open Source Initiative c/o Lawrence Rosen, Esq., 12 3001 King Ranch Road, Ukiah, CA 95482. */ 13 14 #include <errno.h> 15 #include <error.h> 16 #include <fcntl.h> 17 #include <gelf.h> 18 #include <stdlib.h> 19 #include <unistd.h> 20 21 int 22 main (int argc, char *argv[]) 23 { 24 if (argc < 3) 25 error (EXIT_FAILURE, 0, "usage: %s FROMNAME TONAME", argv[0]); 26 27 elf_version (EV_CURRENT); 28 29 int infd = open (argv[1], O_RDONLY); 30 if (infd == -1) 31 error (EXIT_FAILURE, errno, "cannot open input file '%s'", argv[1]); 32 33 Elf *inelf = elf_begin (infd, ELF_C_READ, NULL); 34 if (inelf == NULL) 35 error (EXIT_FAILURE, 0, "problems opening '%s' as ELF file: %s", 36 argv[1], elf_errmsg (-1)); 37 38 int outfd = creat (argv[2], 0666); 39 if (outfd == -1) 40 error (EXIT_FAILURE, errno, "cannot open output file '%s'", argv[2]); 41 42 Elf *outelf = elf_begin (outfd, ELF_C_WRITE, NULL); 43 if (outelf == NULL) 44 error (EXIT_FAILURE, 0, "problems opening '%s' as ELF file: %s", 45 argv[2], elf_errmsg (-1)); 46 47 gelf_newehdr (outelf, gelf_getclass (inelf)); 48 49 GElf_Ehdr ehdr_mem; 50 GElf_Ehdr *ehdr; 51 gelf_update_ehdr (outelf, (ehdr = gelf_getehdr (inelf, &ehdr_mem))); 52 53 if (ehdr->e_phnum > 0) 54 { 55 int cnt; 56 57 if (gelf_newphdr (outelf, ehdr->e_phnum) == 0) 58 error (EXIT_FAILURE, 0, "cannot create program header: %s", 59 elf_errmsg (-1)); 60 61 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt) 62 { 63 GElf_Phdr phdr_mem; 64 65 gelf_update_phdr (outelf, cnt, gelf_getphdr (inelf, cnt, &phdr_mem)); 66 } 67 } 68 69 Elf_Scn *scn = NULL; 70 while ((scn = elf_nextscn (inelf, scn)) != NULL) 71 { 72 Elf_Scn *newscn = elf_newscn (outelf); 73 74 GElf_Shdr shdr_mem; 75 gelf_update_shdr (newscn, gelf_getshdr (scn, &shdr_mem)); 76 77 *elf_newdata (newscn) = *elf_getdata (scn, NULL); 78 } 79 80 elf_flagelf (outelf, ELF_C_SET, ELF_F_LAYOUT); 81 82 if (elf_update (outelf, ELF_C_WRITE) == -1) 83 error (EXIT_FAILURE, 0, "elf_update failed: %s", elf_errmsg (-1)); 84 85 close (outfd); 86 87 return 0; 88 } 89