On Wed, 2019-06-26 at 20:01 +0000, Sasha Da Rocha Pinheiro wrote: > So, I need to write an elf file. I have an open Elf * handle with > read only permission. I then need to update the program headers and > next add a new program header entry. > For that we create an Elf * handle with write permission, and create > the headers doing: > elf64_newphdr(new_elf, old_elf->e_phnum) > for loop: memcpy(newPhdr, oldPhdr, oldEhdr->e_phentsize); > > This is done because prior to memcpy, I perform changes (updates) in > the values in the copied program headers.
Best to do this with: /* Get the number of program headers in the ELF file. If the file uses more headers than can be represented in the e_phnum field of the ELF header the information from the sh_info field in the zeroth section header is used. */ extern int elf_getphdrnum (Elf *__elf, size_t *__dst); Also, if you want to support either 64 or 32 bit ELF files, then using gelf_getphdr () and gelf_updatephdr () in the loop might be better than the memcpy. > Now I need to add a new program header. How can I insert a new > program header to the ones copied to newPhdr? The problem here is > that I need to assess with the updated headers where to place a new > header. It seems I can't call elf64_newphdr again on the new_elf > handle. Yes, if you want to shuffle the phdrs around and/or insert headers then you need to keep around copies of the original headers. You could use your own array of Elf64_Phdr or GElf_Phdr for that. Note that in the case of gelf_getphdr () you already provide your own storage, so that might be another reason to prefer the gelf interfaces. Cheers, Mark