Search code examples
computer-science

What is the return address that is pushed onto the stack if interrupt occurs during the execution of the last instruction of a program?


Computer organisation and architecture

When an interrupt occurs during the execution of a program then the CPU executes that instruction and stores the address of next instruction in the stack and services the interrupt and then again resumes the execution of the previous programs instructions using the help of stack

Now what if the CPU is executing the last instruction of a program and then an interrupt occurs and what return address is pushed onto stack


Solution

  • There does not exist a last instruction of a program.

    The CPU will keep fetching instructions - following whatever path those instructions tell it to.
    Some architecture have a specific instruction to halt the CPU - this is either a permanent halt (so that interrupts are not served anymore) or a temporary halt.
    In the latter case when the CPU resumes it will re-start fetching instructions from the one after the halt and the program must be aware of this.

    In case a program executed inside an operating system, when a program ends it must notify the OS of such condition (may be as simple as doing a return) so that it can "point" the CPU at another program.
    The OS itself never ends, it there is nothing to do, a dummy task is scheduled - usually one that halts the CPU until the next interrupt.
    There are situations where an interrupt should not occur (e.g. while at the begin of processing another interrupt) - in that case they are disabled.

    To put it simple, in the worst a program has to spin in a loop (while (1);) to keep the CPU from fetching behind the end of the code.


    At the architecture level interrupts are served at instruction boundaries, i.e. after the "last" instruction ended and before the "next" one.
    Some architecture may not enforce this but that's a total different ball of wax.
    So when an interrupt is served the state of the CPU is always architecturally defined.
    As an interrupt cannot be served during a ret instruction of a call but rather either before or after, the return address either points to the ret itself (if the interrupt is served before) or to the instruction after the call (if it is server after).