Self-Modifying Code [C ++]

I read a codebreakers magazine article on self-modifying code and there was this piece of code:

void Demo(int (*_printf) (const char *,...))
{ 
      _printf("Hello, OSIX!n"); 
      return; 
} 
int main(int argc, char* argv[]) 
{ 
  char buff[1000]; 
  int (*_printf) (const char *,...); 
  int (*_main) (int, char **); 
  void (*_Demo) (int (*) (const char *,...)); 
  _printf=printf; 
  int func_len = (unsigned int) _main ­- (unsigned int) _Demo; 
  for (int a=0; a<func_len; a++) 
    buff[a] = ((char *) _Demo)[a]; 
  _Demo = (void (*) (int (*) (const char *,...))) &buff[0]; 
  _Demo(_printf); 
  return 0; 
}

This code supposedly executed Demo () on the stack. I understand most of the code, but the part where they assign func_len confuses me. As far as I can tell, they subtract one random pointer address from another random pointer.

Does anyone want to explain?

+5
source share
2 answers

The code relies on knowledge of the layout of functions from the compiler, which can be unreliable with other compilers.

func_len, -, , Demo _Demo ( Demo()) _main ( main()). , Demo, buff. buff , . , _Demo, _main , . , , unsigned int , ; , , uintptr_t <stdint.h> <inttypes.h>.

, , , . , . , , .

, , , . , "" , . , , !

+7

_main _Demo, . , , , .

: .

+5

All Articles