问题
Is there any way to figure out address of machine instruction, that was interrupted by some signal? Assuming that we are at handler established by sigaction()
and have all access to passed siginfo_t
and ucontext_t
.
As far as I see man pages says nothing about it.
回答1:
Not portable. But this is for x86_64:
The structure ucontext_t
contains the value of the register REG_RIP
, which should hold the value you look for. This is the first instruction, which will be executed, after returning from the sighandler.
Other architectures should have similar registers (EIP on x86_32, etc.).
回答2:
Lets see below example for linux and x86 architure
#include<stdio.h>
#define __USE_GNU
#include<signal.h>
#include<ucontext.h>
void myhandle(int mysignal, siginfo_t *si, void* arg)
{
ucontext_t *context = (ucontext_t *)arg;
printf("Address from where crash happen is %x \n",context->uc_mcontext.gregs[REG_RIP]);
context->uc_mcontext.gregs[REG_RIP] = context->uc_mcontext.gregs[REG_RIP] + 0x04 ;
}
int main(int argc, char *argv[])
{
struct sigaction action;
action.sa_sigaction = &myhandle;
action.sa_flags = SA_SIGINFO;
sigaction(11,&action,NULL);
printf("Before segfault\n");
int *a=NULL;
int b;
b =*a; // Here crash will hapen
printf("I am still alive\n");
return 0;
}
Now compile and run and see discompiled instrustion sets.
jeegar@jeegar:~/stackoverflow$ gcc -g test1.c -o test1.o
jeegar@jeegar:~/stackoverflow$ ./test1.o
Before segfault
Signal is 11
Address from where crash happen is 40065b
I am still alive
jeegar@jeegar:~/stackoverflow$ objdump -S test1.o
Here in object dump
printf("Before segfault\n");
400645: bf a8 07 40 00 mov $0x4007a8,%edi
40064a: e8 21 fe ff ff callq 400470 <puts@plt>
int *a=NULL;
40064f: 48 c7 45 f0 00 00 00 movq $0x0,-0x10(%rbp)
400656: 00
int b;
b =*a; // Here crash will hapen
400657: 48 8b 45 f0 mov -0x10(%rbp),%rax
40065b: 8b 00 mov (%rax),%eax
40065d: 89 45 fc mov %eax,-0x4(%rbp)
printf("I am still alive\n");
400660: bf b8 07 40 00 mov $0x4007b8,%edi
400665: e8 06 fe ff ff callq 400470 <puts@plt>
At 40065b address which machine code is there and which line of your code has done this.
Here i have given you and example code, where segmentation happen and on system's Seg fault signal one handler will be called and in that i have fetched the address of last executated machine cycle and print that address. To varify that address i have also shown the object dump of that code and segmentation falt line's machine instruction matches.
I think this is what you want.
来源:https://stackoverflow.com/questions/34989829/linux-signal-handling-how-to-get-address-of-interrupted-instruction