I am trying to use the libelf library under Ubuntu to append a new section that will contain executable code to an existing ELF file. Because the program cannot edit its own ELF file at run-time, I decided to create a copy of the ELF file and just add the new section to the copy. This also lets me understand how ELF files work.

I believe I have successfully copied the PHDR and EHDR correctly (using readelf, the EHDR and PHDR files between the ELF I have originally and the one I copied are the same with the exception of my copied ELF saying the section index of the string table is 0). I’ve come across a problem copying sections from one ELF file to another. From my understanding, each section in an ELF file can hold more than 1 data descriptor. I can use elf_getdata() to iterate and copy each data descriptor within each section, and use elf_nextscn() to iterate across every section in a particular elf file. Using the code below, I can compile just fine. But whenever I run the code, it fails at elf_update() and prints out “main: elf_update()  failed : cannot write data to file.” into the console. I’m stumped at what could be causing the problem.

               Elf *e1,*e2;

Elf_Scn *scn1,*scn2;

Elf_Data *data1,*data2;

GElf_Ehdr ehdr1,*ehdr2;

GElf_Phdr phdr1,phdr2;

GElf_Shdr shdr1,shdr2;


… open/create ELF files, copy EHDR, copy PHDR …

int sndx=1;

                scn1 = NULL;

                printf("Starting to copy sections...\n");


                while ((scn1 = elf_nextscn (e1, scn1)) != NULL) {


                                if (gelf_getshdr(scn1, &shdr1) != &shdr1)

                                                errx (EXIT_FAILURE, "getshdr()  failed : %s.",elf_errmsg ( -1));

if ((scn2 = elf_newscn(e2)) == NULL) {

errx(EX_SOFTWARE, "elf_newscn() failed: %s.",elf_errmsg(-1));

return 0;


if (gelf_getshdr (scn2, &shdr2) != &shdr2)

              errx (EXIT_FAILURE, "getshdr ()  failed : %s.",elf_errmsg ( -1));




                                while ((data1=elf_getdata(scn1,data1))!=NULL){

                                                if ((data2 = elf_newdata(scn2)) == NULL)

                                                                errx (EXIT_FAILURE, "elf_newdata () failed: %s." , elf_errmsg (-1));






                printf("Copied %d out of %d sections.\n", sndx, ehdr1.e_shnum);

                if (elf_update(e2, ELF_C_WRITE) < 0) {

                                errx ( EXIT_FAILURE , "elf_update ()  failed : %s.",elf_errmsg ( -1));

                                return 0;


Bryan Mason