ELF modify section flags

2.4k Views Asked by At

I compiled a C code using gcc and when I check the sections of the ELF using readelf I can see that the flags for .data section are set to WA (Writable and Allocatable).

Is it possible to modify these flags? Can I make this section executable?

I am using gdb to debug this binary and I would like to set the flags for .data section as Executable at a certain point. So, can this be done using either gdb or gcc?

1

There are 1 best solutions below

1
On

Is it possible to modify these flags? Can I make this section executable?

Yes. If you want to do this as a one-off, the simplest approach may be to compile source to assembly, and modify section attributes there, then compile assembly into object file and link as usual.

I am using gdb to debug this binary and I would like to set the flags for .data section as Executable at a certain point.

You also could call mprotect(addr, len, PROT_READ|PROT_WRITE|PROT_EXEC) from within GDB.

Note: modifying the flags in the .data section after the binary has been linked will have no effect whatsoever: the kernel doesn't look at sections, only at PT_LOAD segments.

how to mark the data section as executable in the assembly code? I think, something like this: .section .data,"awx",@progbits.

Yes, that looks correct. Did it not work?

mprotect() not found

Is your executable statically linked? If not, mprotect should be found (in libc.so), and you possibly have a GDB bug. It may help to nudge GDB into finding mprotect if you print &mprotect first.

Also note: mprotect(0x0804a020, 80, PROT_READ, PROT_WRITE, PROT_EXEC) is very different from what I suggested (mprotect takes 3 parameters, not 5). You also need to read man mprotect carefully -- it requires start address to be page-aligned.