agiledragon / gomonkey

gomonkey is a library to make monkey patching in unit tests easy
MIT License
1.93k stars 178 forks source link

A bug about cross page. #71

Closed wathenjiang closed 2 years ago

wathenjiang commented 2 years ago

OS manages memory in units of pages. Code segment not writable, so we should call syscall.Mprotect method in golang.

Blog Monkey Patching in Go tells the reason why we should make the code segment writable.

But the code segment of target may cross pages, as shown in the figure below

crosspage

From https://github.com/agiledragon/gomonkey/blob/master/modify_binary_linux.go#L8, we can find only the page_n will be set to writable, becasue page_n is the start page of code segment, but page_n+1 not. It may casuse problems.


Some ideas come from https://github.com/go-kiss/monkey/blob/master/replace_unix.go#L10

wathenjiang commented 2 years ago

Though in https://github.com/agiledragon/gomonkey/pull/72/commits/ed306ccb3b115fab1fab2b0ed768035895e036a9 provides mprotectCrossPage method, actually only 1 or 2 pages should set to writable, because byte width of JMP [rdx] is very short.

But mprotectCrossPage looks more elegant, what do you think about it?

agiledragon commented 2 years ago

ok