How to copy function instructions and store them in buffer?

58 Views Asked by At

Why isn't this code directly storing the assembly instructions of func into the buffer? The value of the buffer is junk and doesn't change.

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <unistd.h> 
char buffer[1000];
uint64_t* addr; 

void func() { 
// here should be what the function really do
    addr = (uint64_t*)&func; 
    memcpy(buffer, &addr, 1000);  // im expecting that the instructions of func will be stored in the buffer 
    strcpy(secret, hash(secret, buffer)); // secret is previous hash of the function before it so i can make  hash chain to verify the control flow integrity  

    // also the 1000 is not the actual size for the function, i just used it here for clarification 
} 
1

There are 1 best solutions below

0
gulpr On
  • There is no guarantee that the &func will reference the memory you can read.
  • There is no guarantee that memcpy will work with this reference on your platform as function pointers are not data pointers.
  • uint64_t is not the type which is guaranteed to hold the reference to the function converted to this type

But if it works, then your code copies the variable address and next bytes which follow it (and it invokes Undefined Behaviour)

void func() { 
    memcpy(buffer, (void *)&func, 1000); 
    /* ... */
}

This code invoked UB too but it might work on some platforms.