How to access .text section using a function pointer in C? -
i trying inject executable code in memory using c. executable should able read it's own code , copy other location referenced pointer. general template code follows
int main(){ int (*main_ptr)(); main_ptr=main; // make pointer point start of main /* * rest of code. * */ /*now trying print first 10 bytes of main function. * see if possible access main's code. */ for(int i=0;i<10;i++) printf("%x ",*main_ptr++); return 0; }
but output value of pointer (i.e. address of main function), not value points (the code of main function). had read somewhere c not dereference function pointers. not know why. there way around this? or, there way program access own code section?
p.s. understand many may think stupid question , not contribute research , that. i'am trying understand how malware written , given absence of material on web, has been frustrating, decided try myself. great.
there 2 issue code (even though such ub strict). implementations point of view there following issues
none of implementations define
*
operator function pointer.none of implementations define
++
operator on function pointers because size of function not defined.
but implementations define casting fptr void*
, other data pointers though ub.
you can make use of fact.
i tried simple modification of code -
for(i=0;i<10;i++) printf("%x ",*((int*)main_ptr++));
and produced "expected" behavior gcc
(mingw64), compared output against objdump.
finally goes warning none of approaches portable. perhaps there no portable way achieve doing.
if have same code main, 1 way read actual binary (pointed arg[0]
). parse headers find main , read bytes there. since reading file give data pointer there no ub there.
Comments
Post a Comment