开发者

Is it possible to map an address to the result of a function?

I'm writing a NES emulator in C/C++ for Mac OS (I've already writ开发者_StackOverflow社区ten one, so I know the basics). Since many hardware registers are mapped to memory locations, I was wondering if there was some syscall I could use to map an address to the result of a function: when it would be accessed, the function would be called. (I'm pretty sure I can't, but hey, it's worth asking.)

Here is what I'd like to do:

int getStatusRegisterValue()
{
    return 0xCAFEBABE;
}

// obviously, more parameters than just this would be involved I suppose
int* statusRegister = syscall_to_map_function_to_address(getStatusRegisterValue);

// from here on, doing (*statusRegister) should call getStatusRegisterValue and
// return its value
*statusRegister == 0xCAFEBABE;

This project is going to be my try at LLVM, and my goal is to recompile the ROM to LLVM bytecode. That's why it would be convenient if the simple memory access could trigger the function (just like on real NES hardware). The two other obvious possibilities to solve my problem are to either cache the register values and store them in actual memory, or call a function from the recompiled code to map the memory locations to whatever they really are.

Thanks!


Maybe you could try installing a SEGV handler and checking the faulting address there. As I don't use Mac OS I can't help you more.


This almost sounds just like normal function pointers:

typedef int(*function_type)(void);

function_type = &getStatusRegisterValue; // store
int i = function_type(); // call

Different syntax, same idea?


This can't be done in C (or C++, but let's just stick to C for simplicity).

You can "emulate" (ha) this effect with operator overloading and functors with explicit addressing, but it won't be the real thing. There are too many assumptions that must be made about the target function to do this normally.

1) You assume it always returns the same value.

Actually, that's about it. Still though, it's a big assumption to make!


In C++ you can overload the * and -> operators for user-defined classes. Would this allow you to achieve what you want?


You can't trigger functions to be executed on memory access unless you use memory breakpoints (which is really just for debugging, if available on the system).

This is also independent from the programming language, your question is rather aimed at modern computer platforms in general.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜