Chinaunix

标题: 请教一个Linux下C语言内嵌汇编程序的问题 [打印本页]

作者: lazywrite    时间: 2009-11-10 12:04
标题: 请教一个Linux下C语言内嵌汇编程序的问题
下面这个函数,必须要带锁,然后做一些比较赋值之类的操作,使用了lock命令:

  1. unsigned int func(unsigned int oval, unsigned int nval, unsigned int *area)
  2. {
  3.     int rv;

  4.     asm volatile(
  5.         "lock;"                               ///////////////问题 - -!
  6.         "cmpl %2, %3;"
  7.         "je .L2;"
  8.         "movl $0, %0;"
  9.         "jmp .L3;"
  10.         ".L2:;"
  11.         "movl $1, %0;"
  12.         "movl %2, %1;"
  13.         ".L3:;"
  14.         : "=$A" (rv), "=r" (*area)
  15.         : "r" (oval), "r" (nval)
  16.         : "%eax"
  17.         );

  18.         return rv;
  19. }

  20. int main() {
  21.     unsigned int oval = 1;
  22.     unsigned int nval = 2;
  23.     unsigned int area = 3;

  24.     func(oval, nval, &area);

  25.     return 0;
  26. }
复制代码


问题出在第一行汇编代码lock,删除这句,程序功能上是没问题的(至少我运行过后结果是正确的),但是加上这一句,就会报错,说是无效的指令: Illegal Instruction.

这是另外一个函数,我看不出使用上有什么区别,但是编译运行就没有问题:

  1. unsigned int atomic_add(unsigned int *area, int val)
  2. {
  3.     asm volatile(
  4.         "lock;"
  5.         "addl %1,%0"
  6.         : "+m" (*area)
  7.         : "ir" (val));
  8.         return *area;
  9. }


复制代码


不明白是为什么,请指教,谢谢。

[ 本帖最后由 lazywrite 于 2009-11-10 12:07 编辑 ]
作者: openspace    时间: 2009-11-10 12:26
标题: 回复 #1 lazywrite 的帖子
看看Intel手册吧
似乎lock不支持cmp
作者: lazywrite    时间: 2009-11-10 12:45
原帖由 openspace 于 2009-11-10 12:26 发表
看看Intel手册吧
似乎lock不支持cmp



The LOCK prefix can be prepended only to the following instructions and only to those
forms of the instructions where the destination operand is a memory operand: ADD,
ADC, AND, BTC, BTR, BTS, CMPXCHG, CMPXCH8B, DEC, INC, NEG, NOT, OR, SBB,
SUB, XOR, XADD, and XCHG.


好像还真是这个原因,非常感谢。





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