On Friday, 4 October 2013 at 19:58:54 UTC, Alan wrote:
fault) I've seen ways to do this in Linux and Windows in C/C++ but I have no clue where to start with this in D.

You can often almost copy+paste code from C into D and get it working. My guess is the C examples use mmap on Linux and VirtualAlloc to do it on Windows.

You can call those same functions from D as well. Most you might have to do is copy some declarations from C, but these are in druntime so you'll be ok.

For example, a working Linux program would be like this:

import core.sys.posix.sys.mman;

void main()
{
// the operating system mmap call lets us set the executable flag uint* opcodes = cast(uint*) mmap(null, 4096, PROT_EXEC | PROT_WRITE, MAP_PRIVATE | MAP_ANON, 0, 0);
        scope(exit)
                munmap(opcodes, 4096); // free when we're done - scope(exit) rox
        opcodes[0] = 0xCC;
// you did a delegate before, but you really should use a function // because delegates expect more state that won' really be here
        void* function() func = cast(void* function()) opcodes;
        func();
}


and you get the breakpoint trap when you run it, which is what opcode 0xcc is supposed to do.



And a working Windows program would look like this:

import core.sys.windows.windows;
void main() {
       // VirtualAlloc and mmap are very similar functions...
uint* opcodes = cast(uint*) VirtualAlloc(null, 4096, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
        scope(exit)
        VirtualFree(opcodes, 4096, MEM_RELEASE);

        // and the rest is the same
        opcodes[0] = 0xCC;
        void* function() func = cast(void* function()) opcodes;
        func();
}

Reply via email to