Anil
Anil

Reputation: 31

How to implement detour functions in Linux

My requirement is to patch a function during runtime which is equivalent to K-Patch but for application code. in K-Patch vedio ( https://www.youtube.com/watch?v=juyQ5TsJRTA ) it mentioned @ 1:41 it using functionality which used for traditional used for tracing (noop) beginning of the function. where we can register the handler to call new function definition.

In Windows It looks something like this: (http://www.ragestorm.net/blogs/?p=17)

0005951e (01) 90                      NOP
0005951f (01) 90                       NOP
00059520 (01) 90                      NOP
00059521 (01) 90                      NOP
00059522 (01) 90                      NOP
00059523 (02) 8bff                   MOV EDI, EDI
00059525 (01) 55                      PUSH EBP
00059526 (02) 8bec                  MOV EBP, ESP

I wrote a simple function in Linux (2.6.32-431.el6.x86_64) in which i dont see any NOP instruction which we can used to dynamically patch a new function.

0000000000400554 <mysym>:
400554:       55                      push   %rbp
400555:       48 89 e5                mov    %rsp,%rbp
400558:       b8 98 06 40 00          mov    $0x400698,%eax
40055d:       be 9b 06 40 00          mov    $0x40069b,%esi
400562:       48 89 c7                mov    %rax,%rdi
400565:       b8 00 00 00 00          mov    $0x0,%eax
40056a:       e8 c9 fe ff ff          callq  400438 <printf@plt>
40056f:       c9                      leaveq 
400570:       c3                      retq   

Is there any compiler options or equivalent instructions exists in linux where every functions has some NOP instructions which used to hook up a new function by replacing NOP with near/far JUMP?

Upvotes: 3

Views: 1301

Answers (1)

Max Truxa
Max Truxa

Reputation: 3478

The question is less a "Linux" one but more a "GCC" one.

GCC provides the ms_hook_prologue function attribute (online reference) which is pretty much the same as the /hotpatch compiler option for cl.exe (the MS compiler) but on a function level.

Example:

__attribute__((ms_hook_prologue)) void foo() { }

If you want to use this on more than a few functions you could create a macro to hide the attribute:

#define HOTPATCHABLE    __attribute__((ms_hook_prologue))

Upvotes: 2

Related Questions