使用内联汇编的寄存器输出归零

时间:2017-01-13 18:35:09

标签: gcc assembly x86 inline-assembly intel-syntax

我已经完成了几个线程,而且一切似乎措辞正确......但我的output_01返回false。似乎内联汇编正在为我的变量写零...而我无法弄清楚原因。下面是调用程序集的主c文件中的代码,以及它调用的程序集(并在头文件中抛出,但我不认为它有任何影响......但是魔鬼在细节中是吗?

主文件

#include stdio.h
#include "lab.h"

int output_01();

int main()
{
  printf("Starting exercise lab_01:\n");
  if(output_01())
    printf("lab_01: Successful!");
  else
    printf("lab_01: Failed!");
  return 0;
}

int output_01()
{
  int eax=0;
  int edx=0;
  int ecx=0;


  asm("call lab_01;"
      "mov %0, eax;"
      "mov %1, edx;"
      "mov %2, ecx;"
      :
      :"r" (eax), "r" (edx), "r" (ecx)
      :
  );
  if(eax==3 && edx==1 && ecx==2)
  {
    printf("\teax = %i\n",eax);
    printf("\tedx = %i\n",edx);
    printf("\tecx = %i\n",ecx);
    return 1;
  }
  else
  {
    printf("\teax = %i\n",eax);
    printf("\tedx = %i\n",edx);
    printf("\tecx = %i\n",ecx);
    return 0;
  }
}

程序集文件

BITS 32         ;you must specify bits mode
segment .text   ;you must specify a section
GLOBAL lab_01, labSize_01
    lab_01:
        ;instructions:
        ;the following registers have the following values:
        ;eax = 1
        ;edx = 2
        ;ecx = 3
        ;Make it so that the registers have the following values, using only the allowed opcodes and registers:
        ;eax = 3
        ;edx = 1
        ;ecx = 2
        ;Allowed registers: eax,ebx,ecx,edx
        ;Allowed opcodes: mov, int3
        ;Non volatile registers: ebp, ebx, edi, esi
        ;Volatile registers: eax, ecx, edx
        ;Forbidden items: immediate values, memory addresses
        ;;;;;;;;;;;;; EXERCISE SETUP CODE - DO NOT TOUCH
        int3 ;make it 'easier' to debug
        push ebx; this is to save ebx onto the stack.
        mov eax, 1
        mov edx, 2
        mov ecx, 3
        ;;;;;;;;;;;;; YOUR CODE BELOW
        ;int3 ;make it 'easier' to debug
        mov ebx, eax ;hold 1
        mov eax, ecx ;eax is set 3
        mov ecx, edx ;ecx is set to 2
        mov edx, ebx ;edx is set to 1
        int3 ;make it 'easier' to debug
        ;;;;;;;;;;;;; YOUR CODE ABOVE
        pop ebx;
        ret
labSize_01 dd $-lab_01 -1

lab.h文件:

extern int lab_01();

1 个答案:

答案 0 :(得分:2)

您仅将寄存器列为输入。你根本没有输出。正确的asm是:

asm("call lab_01;"
      : "=a" (eax), "=d" (edx), "=c" (ecx)
  );