Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What to do in interrupt handler for divide by zero?

What should an operating system interrupt handler do for interrupts related to coding mistakes?

For example, I tried to divide by 0 for testing my interrupt and my interrupt handler got called. However, because the div instruction was not successfully executed, EIP is not updated to the next instruction after it and after returning from the interrupt handler with iret, it goes back to the erroneous div instruction again.

  mov ax, 3
  mov dl, 0
  div dl    ; go back here again and again

What is the correct way to handle this interrupt? A few ways I thought of:

  • Change dl to something else other than 0. However, I'm not sure if dl can keep if something happens, and interrupt routine is supposed to restore registers after exit, and I don't think silently correct an error by providing wrong computation is good.

  • Retrieve the next instruction after div. However, I haven't thought of any simple and reliable way to get the next instruction.

  • Modify the top of the stack that is currently containing the return address to the address of some other code. So, we do not go back to div instruction anymore.

like image 380
Tu Do Avatar asked Dec 25 '22 13:12

Tu Do


1 Answers

You are right that none of those are particularly good things to do in the case of this particular interrupt. As mentioned in the comments, since you have the address of the instruction you could fetch whatever is at that address, decode the instruction and then advance the pointer to the next address .... but the code won't have been expecting that!

In POSIX operating systems this exceptional behaviour is covered by the SIGFPE signal. If you were writing an OS and wanted to follow POSIX then your interrupt handler should send that signal to the process. If the process has a handler for that signal then jump to that and allow the process to handle this (for example, that is how a try/catch block in a high level language could work .... now you know why exceptions are slow!). If there is no signal handler then the process should be killed (and re-enter your scheduler to work out what to do next ... and hope it was PID 1!).

Of course, this is your OS, and there's no reason you have to follow POSIX if you don't want to! If you have some other fancy way to handle an error in a user program then you can implement that instead.

like image 79
dave Avatar answered Dec 31 '22 14:12

dave