views:

36

answers:

2

Could the own heap space be readed? could the software be self modified in memory?

I write some code to show the subject,

am I reading own code at memory? how (if possible) to write it and change instruction on runtime?

#include<stdio.h>
#include<stdint.h>

volatile int addressBase;
uint8_t read(int address);


int main(void) {

    printf("Helium word");

    addressBase=(int)&main;        
    printf("[%X]", read( 0 ));         
    getchar();

    return 0;
}


uint8_t read(int address)
{

       const uint8_t *addr;                        
       addr=(const unsigned char *)(addressBase+(int)address);
       return (*addr);
}
+1  A: 

Memory is normally divided into read-only instruction memory and writable data memory which may or may not be executable. If you application wants to write and then run its own code (like a JIT compiler), you will probably need to use some operating specific method of obtaining the necessary memory block. So yes you can read your own instructions but I highly doubt you will be able to modify them.

doron
Agree, seems to be that way
Hernán Eche
+1  A: 

You can read and write heap space at your own risk.

Self-modifiying code might be a useful trick in restricted, small environments like small embedded systems. Modern desktop or server CPUs however do not like self-modifying code at all because it breaks instruction caching, prefetching and pipelining. One anecdote: TI-Scheme ran blazingly fast on 386 CPUs. It used self-modifying code. 486 CPUs introduced instruction caching and TI-Scheme crashed.

Peter G.
I seem to remember that, under Windows, there is an API function to tell the OS part of the executable memory has been modified so that the OS can void its caches.
yes..I think this could be done with no Operative System (and proper memory block definition at linker) but having an operative system in the middle, is very hard to know what is happening behind
Hernán Eche
so where does JIT compilation fit into this?
doron