如何实现控制流
所谓的Control flow其实就是program counter
我们常常听到Control flow,维基百科的Control flow对它的总结是非常全面的,从high-level programming language级别(在high-level programming language中有control flow statement,比如return、goto等),到machine language级别(这是最底层了;以x86 为例,JMP 指令,更多参见X86 Assembly/Control Flow)。在本文中,我们重点关注的是machine language级别,正如其所总结的:
At the level of machine language or assembly language, control flow instructions usually work by altering the program counter. For some central processing units (CPUs), the only control flow instructions available are conditional or unconditional branch instructions, also termed jumps.
CPU的program counter默认行为是:自加1的,所以程序默认是顺序执行即可(编译器编译生成的machine language program其实是顺序的),通过control flow instruction,可用改变这种默认行为,从而实现各种执行flow。
一个例子是在OS书的4.1. The Role of Interrupt Signals
As the name suggests, interrupt signals provide a way to divert the processor to code outside the normal** flow of control**. When an interrupt signal arrives, the CPU must stop what it's currently doing and switch to a new activity; it does this by saving the current value of the program counter (i.e., the content of the eip and cs registers) in the Kernel Mode stack and by placing an address related to the interrupt type into the program counter.
正在不同的层次来看待本质上相同的事情,在program language层,我们把它叫做flow of control,在指令层,我们它其实是program counter。