I am working with processes and i need to replace function in text segment, but if function will be larger then old it could overwrite something. So i wont to paste new function somwhere in virtual memory and then change pointers from old function. For example to put function in HEAP or make TEXT larger and add new function to the end of TEXT? Any ideas?
Asked
Active
Viewed 176 times
0
-
2Sure, usually there are unmapped pages before and/or after the .text section, and almost certainly one within +-2GiB so within rel32 range of every other .text page. Probably best to (atomically) overwrite the first 5 instruction bytes of the function with a jump to your new code, instead of trying to find and rewrite every call to it. – Peter Cordes Mar 19 '21 at 03:28
-
thank you for answer @PeterCordes absolutely i will better overwrite first bytes with jump instructions, then trying to overwrite each call :) Maybe you have some references about how to use that unmapped pages to make TEXT larger? Because, what you wrote it sounds good, but in practice i cant imagine how to map that pages to TEXT. Or what the best way to serf it on the web?) – ipolit__ Mar 19 '21 at 14:51
-
Not something I've done, but I'd guess just parse `/proc/
/maps` to find where the text section is. From inside the process, you can just `mmap( addr, ..., MAP_ANONYMOUS)` with a non-NULL hint address (but without MAP_FIXED) - if it gives you an address other than what you asked for, and it's too far away, then munmap and try again somewhere else. From outside the process, IDK how to call mmap on behalf of another process. Might have to use ptrace to inject code to make the call, then call it, like GDB would when you do `print foo()` and it has to run a function in the target context – Peter Cordes Mar 19 '21 at 14:59 -
1From google search results for `site:stackoverflow.com linux inject code into other process`, [Inject code into process in ubuntu 64bit](https://stackoverflow.com/q/40427094) apparently has some working code using ptrace, and the only problem was injecting useful machine code (position-independent). However, that just overwrites whatever code follows the current RIP at the time it happens to attach, not allocating a new page. You could maybe use space below RSP in the stack region to inject a little bit of code that does your mmap, and single-step it from the controlling process. – Peter Cordes Mar 19 '21 at 15:06
-
IDK if there's an easier way to get pages allocated in the target process, or to run arbitrary code or at least system calls. – Peter Cordes Mar 19 '21 at 15:09