3 ms·
it winds up being about the same. you need a pointer-wide atomic compare-and-swap (CAS) to swap out the function pointer safely. on x86_64, a pointer-wide valu
by munin 11y ago
it winds up being about the same. you need a pointer-wide atomic compare-and-swap (CAS) to swap out the function pointer safely.
on x86_64, a pointer-wide value is 8 bytes, which is enough space to put some instructions that detour to another function. so it's a question of whether you CAS the global function pointer, or the first 8 bytes of the function.
the "atomic CAS" part means you don't benefit from caching either, since you need to make sure the write is globally visible or threads on different cores will do different things. this kind of trickery combines two terrible things: reasoning about virtual method invocation (essentially) and lock-free programming techniques. have fun!
- openasocket 11y agoWhy do you need a CAS? Isn't an atomic write sufficient? Because we're just changing the function to use our code we don't really care what it was pointing to before, and we don't care if someone else changed the pointer before we did: it's just last write wins. In fact, the function pointer method will be able to have multiple threads try to hotpatch at once; idk about the OP code. My guess is the OP's method can probably be extended to allow for more advanced hooking, like returning to the original function definition after running the new code or something. And, it means the caller doesn't have to know that the function is hot patchable, which I'm guessing is the most likely reason.