This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

how to build executable instructions blocks dynamically ?


Hello,



I'm sorry if the answer has already been given, but I have found an answer
written in 2002 for PowerPC ; and it doesn't work on my laptop  :'(


I want to build executable instructions blocks dynamically, in order to use
the "preparations sequences" in a virtual machine.
I want to create a buffer and to put some code into it.



Until now, I've thought (with some help) about doing this :

---------------------------

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include <sys/types.h>
#include <signal.h>
#include <sys/mman.h>
#include <fcntl.h>

typedef void (*FUNCTYPE)(void);

void testBuildFunc() {
        size_t size = &&block_end - &&block_begin;
#ifndef NOT_MMAP
    unsigned char* buf = mmap(NULL, size, PROT_EXEC|PROT_READ|PROT_WRITE,
MAP_PRIVATE|MAP_ANON, -1, 0);
    if (buf == MAP_FAILED) {
        perror("mmap");
        exit(EXIT_FAILURE);
    }
#else
        unsigned char* buf = malloc(size);
        if (buf == NULL) {
                perror("malloc");
                exit(EXIT_FAILURE);
        }
        if (mprotect(buf,size,PROT_EXEC|PROT_READ|PROT_WRITE) != 0) {
                perror("mprotect");
                exit(EXIT_FAILURE);
        }
#endif
    if (buf == MAP_FAILED) {
        perror("mmap");
        exit(EXIT_FAILURE);
    }
        unsigned char* beginBuf = buf;
        unsigned char* done = &&block_end;
        memcpy(buf,&&block_begin,size);

        if (msync(block,size,MS_INVALIDATE) != 0) {
                perror("msync");
                exit(EXIT_FAILURE);
        }

        int i=1;
        FUNCTYPE fn = (FUNCTYPE) beginBuf;
        fn();
        printf("%d\n",i);
        goto *done;

block_begin: {
        int j = 0;
}
block_end:
        return;
}

------------------------


I have found an answer using cacheflush... but I haven't managed to install
it on my laptop. (centrino cpu with GNU/Linux os)



If someone could help me, it will help me :-)


Thanks
Regards.





Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]