Search code examples
assemblyx86mipsprocessor

How does processors know the end of program?


I was wondering, how does processors know when to stop executing a program. Or rather, when to stop the "fetch, decode execute" cycle.
I have thought of different ways but not sure which is the correct one or if they are all wrong.
1- Maybe there is a special instruction at the end automatically added by the assembler to let the processor know this is the end.
2- When it reach an invalid memory (But how does it recognize that).
3- It loops and re-run the program, but again how does it recognize when to loop or maybe it is added by the assembler automatically.
4- Or maybe it doesn't stop at all, it will keep running for ever. (But isn't that power inefficient?

Please advice.
If the answer may vary from processor to processor, lets take MIPS and x86 as an example.

Thanks.


Solution

  • This depends on the operating system and the processor.

    For a processor with a halt instruction (like X86) when all processes and threads are in a wait state (nothing to do), the operating system may execute a halt instruction, which will halt the cpu and wait for an interrupt. If the next interrupt doesn't result in switching the state of any thread to runnable, then the operating system will go back to the halt instruction.

    On a cpu without a halt instruction, when all threads are waiting, the operating system goes into an idle loop that just branches to itself.

    Getting back to the original question, the basic sequence for running a program is to do an initial allocation of memory space for a program, load a program, then call the program. The program should eventually return from the call back to the operating system, and the operating system will release the memory that was allocated to run the program. An operating system may also create a virtual address space during the initial allocation phase.

    Further reading

    wiki loader , wiki program execution. In the case of MSDOS, a program used an INT software sequence to return back to MSDOS, such as setting AH = 04Ch and then doing an INT 21H. For other operating systems, the loader does a call to the program, which returns when it's complete.