0

i try to make a function with a strange way , but i am believe the there exist a way to do it. i try to create function fn()=1;

int fn()
{
     return 0;
}

then i try to compile it without main then disassembled

gcc -Wall -c fn.c
objdump -d ./a.out

the result is :

./fn.o:     file format elf64-x86-64


Disassembly of section .text:

0000000000000000 <fn>:
0:  55                      push   %rbp
1:  48 89 e5                mov    %rsp,%rbp
4:  b8 01 00 00 00          mov    $0x1,%eax
9:  5d                      pop    %rbp
a:  c3                      retq 

then i write my program:

#include <stdio.h>
#include <stdlib.h>
union datas{
    char * v;
    int (*d)();
}ptr;

int main()
{
    int (*f0)();

    ptr.v=(char *)malloc(11);
    ptr.v[0]=0x55;
    ptr.v[1]=0x48;
    ptr.v[2]=0x89;
    ptr.v[3]=0xe5;
    ptr.v[4]=0xb8;
    ptr.v[5]=0x01;
    ptr.v[6]=0x00;
    ptr.v[7]=0x00;
    ptr.v[8]=0x00;
    ptr.v[9]=0x5d;
    ptr.v[10]=0xc3;
printf("ok1\n");//check
    f0=ptr.d;
printf("ok2\n");//check
    printf("fn=%d\n",f0());
printf("ok3\n");//check
    return 0;
}

but the result is:

ok1
ok2
Segmentation fault (core dumped)
Peter Cordes
  • 328,167
  • 45
  • 605
  • 847

1 Answers1

-3

It won't work because you cannot mix pointer types in c (a strongly-typed language). Moreover, c does not allow mixing code and data at all. You want that? Try lisp.

  • This isn't the problem; what the OP is trying would work on an x86 C implementation where `malloc` returned memory from pages with read/write/execute permission. (e.g. on an old CPU that doesn't support the NX page-table bit, or with an OS that uses the legacy page-table format), The OP isn't trying to treat data as *C* code (like `eval` in perl or other dynamic languages). – Peter Cordes Nov 27 '17 at 11:56
  • LOL. :) I wouldn't say C is perfect fit for the intent of the OP, but definitely do-able. Actually mixing pointer types in C is so easy to do, that it's usually source of many bugs in SW. – Ped7g Nov 27 '17 at 11:56
  • [Here's an example](https://stackoverflow.com/a/1154595/224132) of doing exactly the same thing that someone posted as an answer a while ago, presumably tested on an OS / C implementation where dynamically allocated memory is executable by default – Peter Cordes Nov 27 '17 at 12:14