The title kind of explains it all: How do I catch segfaults in Linux from scratch in assembly? Lets say the error I'm trying to catch is a segfault from writing to illegal memory.
Asked
Active
Viewed 337 times
1
-
2Welcome to SO! Perhaps you could show what have you already tried that didn't work. By "catching" a segmentation fault I imagine adding a signal handler for SIGSEGV (in *nix), which you do by means of calling `sys_signal`, but more context would be needed. – istepaniuk Sep 14 '21 at 14:30
-
1Sorry, I haven't tried anything yet because I don't know where to start. Lets say you try to write to memory you aren't allowed to in Linux, how would you catch that? – Aristomenes Angeletakis Sep 14 '21 at 14:34
-
1@AristomenesAngeletakis Normally you simply don't write to memory you are not allowed to write. But if you want to catch such a case, handle the relevant signal. There are two, `SIGBUS` and `SIGSEGV` that are relevant in this case. – fuz Sep 14 '21 at 19:25
-
1I'd suggest starting out by implementing in C instead of assembly. Briefly, you use `sigaction` to register a signal handler for SIGSEGV and/or SIGBUS, a function that will be called by the kernel when the fault occurs. The arguments to this function include structures containing the state of the program at the point of the fault, e.g. RIP value, faulting address, register contents. Your handler function can modify the program state and resume, or abort, or maybe some other options (e.g. `longjmp`). – Nate Eldredge Sep 14 '21 at 19:30
-
1But trying to do it in assembly right away will just add a level of complexity and inconvenience on top of something that's already rather complicated and not always well documented. Take it one step at a time. – Nate Eldredge Sep 14 '21 at 19:31
-
1Start with the man pages for `sigaction(2)` and `signal(7)`. The program state is in the machine-specific `mcontext_t` structure; you may have to read kernel headers or source code to determine its members. In assembly you have to work out the layout of all these structures yourself (offsets of the relevant members) and hardcode them into your asm, which is a pain. – Nate Eldredge Sep 14 '21 at 19:35
-
An important thing to clarify - once you have caught the illegal access, what do you want to do about it? – Nate Eldredge Sep 14 '21 at 19:36
-
Thank you so much for the responses! To clarify, I just want to exit when I catch a signal error. – Aristomenes Angeletakis Sep 15 '21 at 14:37