Search code examples
exceptionoperating-systemos-trap

Difference between TRAP and exceptions


Taking an Operating System course. So I've understood both TRAPs and exceptions can be considered software interrupts... so they are both internal and synchronous. However I can't seem to figure out the difference between the two definitions. So if anybody wouldn't mind explaining and giving some examples it'd be highly appreciated.

Thanks.


Solution

  • There are interrupts - things that cause the CPU to start executing code from a table (ae.g. n interrupt vector table).

    Interrupts can be split into categories depending on what triggered them:

    • exceptions - triggered by the CPU itself
    • IRQs - triggered by external hardware (e.g. network card)
    • software interrupts - triggered explicitly by the code that was running
    • IPIs (inter-processor interrupts) - triggered by a different CPU

    Exceptions can be further broken down into sub-categories:

    • aborts - things that prevent the interrupted code from continuing. These are things that indicate a major problem - e.g. division by zero, hardware failures, etc.
    • traps - things that don't prevent the interrupted code from continuing. These can be used for debugging, for virtual memory management, etc.

    Mostly; the difference between a trap and an exception is like the difference between a car and a vehicle (a trap is one kind of exception, and a car is one type of vehicle; but there are exceptions that aren't traps and there are vehicles that aren't cars).

    So I've understood both TRAPs and exceptions can be considered software interrupts

    This is probably wrong (definitely wrong if you're using Intel's terminology) - a software interrupt is a type of interrupt and not a type of exception. A nice example of this is the difference between an int3 instruction and an int 3 instruction on 80x86. The int3 triggers a breakpoint exception (a trap) while the int 3 is a software interrupt (not a trap and not an exception) that will probably (depending on the OS) result in a general protection fault (due to violating the "descriptor privilege level" restriction on corresponding interrupt descriptor table's entry).