cpointersmetaprogrammingheap-memoryself-modifying

Reading/Writing self heap


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);
}

Solution

  • 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.