- 论坛徽章:
- 1
|
本帖最后由 yangPSO 于 2014-01-24 17:09 编辑
首先感谢2位的回复!
对于“为什么在Linux-2.4.0中宏switch_to保存的是esi、edi和ebp等几个寄存器,而在linux-2.6.10中宏switch_to保存的却是esi和eflags。”
的问题,在新版本的内核中,例如Linux-2.6.31中,所有的寄存器都会保存(不知道早先的版本未全部保存寄存器出现过什么BUG):
/*
* Saving eflags is important. It switches not only IOPL between tasks,
* it also protects other tasks from NT leaking through sysenter etc.
*/#define switch_to(prev, next, last) \
do { \
/* \
* Context-switching clobbers all registers, so we clobber \
* them explicitly, via unused output variables. \
* (EAX and EBP is not listed because EBP is saved/restored \
* explicitly for wchan access and EAX is the return value of \
* __switch_to()) \
*/ \
unsigned long ebx, ecx, edx, esi, edi; \
\
asm volatile("pushfl\n\t" /* save flags */ \
"pushl %%ebp\n\t" /* save EBP */ \
"movl %%esp,%[prev_sp]\n\t" /* save ESP */ \
"movl %[next_sp],%%esp\n\t" /* restore ESP */ \
"movl $1f,%[prev_ip]\n\t" /* save EIP */ \
"pushl %[next_ip]\n\t" /* restore EIP */ \
__switch_canary \
"jmp __switch_to\n" /* regparm call */ \
"1:\t" \
"popl %%ebp\n\t" /* restore EBP */ \
"popfl\n" /* restore flags */ \
\
/* output parameters */ \
: [prev_sp] "=m" (prev->thread.sp), \
[prev_ip] "=m" (prev->thread.ip), \
"=a" (last), \
\
/* clobbered output registers: */ \
"=b" (ebx), "=c" (ecx), "=d" (edx), \
"=S" (esi), "=D" (edi) \
\
__switch_canary_oparam \
\
/* input parameters: */ \
: [next_sp] "m" (next->thread.sp), \
[next_ip] "m" (next->thread.ip), \
\
/* regparm parameters for __switch_to(): */ \
[prev] "a" (prev), \
[next] "d" (next) \
\
__switch_canary_iparam \
\
: /* reloaded segment registers */ \
"memory"); \
} while (0)
至于为什么下面的语句可以保存原寄存器的值
/* clobbered output registers: */ \
"=b" (ebx), "=c" (ecx), "=d" (edx), \
"=S" (esi), "=D" (edi)
下面的这段话很受启发:
“我的理解:巧妙利用编译器特性实现按需保存。
在编译时,如果在分析switch_to前面的代码时,gcc已经将%ebx、%ecx、%edx、%esi、%edi这几个寄存器分配给其他的变量,由于此处要向寄存器写入值(变量ebx、ecx、edx、esi、edi的值写入对应寄存器),故gcc将被迫在asm块前部产生push、后部产生pop操作。又由于变量ebx、ecx、edx、esi、edi本身的值是不确定的,故相应的mov操作也被优化掉了。
这样的结果是,只有必要保存的寄存器值被保存,不相关的寄存器(没有被分配给变量的)值没有被保存。
也就是说,switch_to放在不同的上下文中会产生不同的代码,当然也可能恰好所有的寄存器都不需要保存,即不产生保存操作。”
【原帖:http://bbs.chinaunix.net/thread-3749118-2-1.html】
|
|