I have the following assembly function (shown with objdump already)
0000000000000000 <add>:
0: b8 06 00 00 00 mov $0x6,%eax
5: c3 retq
Now in C I made the following code:
#include <stdio.h>
typedef int (*funcp) (int x);
unsigned char foo[] = {0xb8,0x06,0x00,0x00,0x00,0xc3};
int main(void)
{
int i;
funcp f = (funcp)foo;
i = (*f);
printf("exit = %d\n", i);
return 0;
}
In the global variable foo I typed the memory address of my function in assembly and tried to execute it but it does not return 6 as expected. How can I execute functions for their memory addresses? furthermore, where can i research more on the subject?
obs: sometimes I got the Segmentation fault (core dumped) error
()to call a function.gcc -z execstack temp1.cworks for me. I get6as output.-z execstackon Linux made all readable pages executable until very recent kernel versions. Linux's ELF program loader set the read-implies-exec process "personality" flag when seeing the executable GNU stack metadata. Linux default behavior against `.data` section -PT_GNU_STACK == RWXno longer implies exec-all; I just updated my Arch Linux andgcc -zexecstackdoesn't make .data (or.rodata) executable. See also Unexpected exec permission from mmap....__attribute__((section(".text")))works. I get Assembler messages: /tmp/ccNetmKQ.s:28: Warning: ignoring changed section attributes for .text but it does run. godbolt.org/z/draGeh. On my desktop,-Wl,-Nmakes it fail to link:/usr/bin/ld: cannot find -lgcc_s. Both of those things (array in text section, and read/write text section) would be necessary for a non-const executable array.