HeadlinesBriefing favicon HeadlinesBriefing.com

Go Function Redefinition: Monkey Patching in Compiled Languages

Hacker News: Front Page •
×

A developer demonstrates how Go functions can be dynamically redefined at runtime despite being a compiled language. Using low-level memory manipulation and assembly instructions, the author shows how to replace `time.Now` with a custom function that always returns 5 PM. This technique bypasses Go's lack of native monkey patching support.

Perl once allowed this through its flexible function rewriting capabilities, but the practice earned a bad reputation for creating hard-to-debug code. The Go approach requires finding the function's memory address, modifying page permissions with `mprotect`, and inserting a `JMP` instruction to redirect execution. The implementation works on x86 and ARM64 architectures, though Windows requires different system calls.

Several limitations emerge: inline functions, generic functions, and methods resist this technique. The compiler's optimization passes can inline functions like `fmt.Printf`, making them unreachable through normal function pointers. While technically impressive, this approach trades maintainability for flexibility and should be used sparingly in production code.