Chinaunix

标题: x86的hlt指令不可用 [打印本页]

作者: garyv    时间: 2011-05-30 01:05
标题: x86的hlt指令不可用
我在虚拟机里面编译一个c文件(基于x86 gcc),里面有一条据说是x86的停机指令hlt,如下:
  1. int main(...)

  2. {

  3.     ......



  4.     __asm volatile

  5.     (

  6.         "hlt"

  7.     );



  8.     return 0;

  9. }
复制代码
代码编译正常,但运行时提示"Segmentation fault",莫非这是一条特权指令?
作者: liuiang    时间: 2011-05-30 08:44
Since issuing the HLT instruction requires ring 0 access, it can only be run by privileged system software, such as the kernel.
作者: cjaizss    时间: 2011-05-31 14:48
这些涉及到硬件特权的指令,当然不可能如此随便
作者: heixia108    时间: 2011-06-07 00:08
搜了一下为什么编译出来的可执行文件有hlt,却要在_exit里退出了

http://stackoverflow.com/questions/5213466/why-does-gcc-place-a-halt-instruction-in-programs-after-the-call-to-main

After main returns, exit will be called. The hlt is there in case the system's version of exit doesn't stop execution of the process immediately. In user mode, it will cause a protection fault, which will kill the process. If the process is for some reason running in ring 0, it will just stop the processor until the next interrupt, which will hopefully trigger the OS to remove the process. In processes designed to run in ring 0, there is often a jmp instruction after the hlt which will cause the hlt to be performed over and over until the process is terminated.

作者: smalloc    时间: 2011-06-08 19:41
查下手册不就知道了
The HLT instruction is a privileged instruction. When the processor is running in
protected or virtual-8086 mode, the privilege level of a program or procedure must
be 0 to execute the HLT instruction.
作者: smalloc    时间: 2011-06-08 19:46
其实HLT的行为就代表不能在用户态执行
An enabled interrupt (including NMI and SMI), a debug exception, the BINIT# signal, the INIT#
signal, or the RESET# signal will resume execution. If an interrupt (including NMI) is
used to resume execution after a HLT instruction, the saved instruction pointer
(CS:EIP) points to the instruction following the HLT instruction.




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2