汇编程序 - 传递参数并在程序中使用它

时间:2011-11-06 14:05:02

标签: assembly x86

我写了一个小的assember程序,它获取并输入文件,输出文件和替代参数(-a或-l)。 现在我想在程序中区分用户是否已通过-a或-l。我知道我可以将参数传递给,例如%eax,如下所示:

movl 16(%ebp),%eax

但现在我不知道如何将%eax与-a或-l进行比较以检查传递的参数。 该程序在32位Linux操作系统上运行。

有人可以给我一个暗示吗?

提前致谢,

enne

编辑:我有一个x86处理器。以下是代码的一些相关部分

 .section .data 
#######PROGRAM CODE###

.section .text

#STACK POSITIONS
.equ ST_SIZE_RESERVE, 8
.equ ST_FD_IN, 0
.equ ST_FD_OUT, 4
.equ ST_ARGC, 8      #Number of arguments
.equ ST_ARGV_0, 12   #Name of program
.equ ST_ARGV_1, 16   #Input file name
.equ ST_ARGV_2, 20   #Output file name
.equ ST_ARGV_3, 24   #-a or -l or nothing
.equ ST_EXIT_CODE, 28   #Exit code

.globl _start
_start:
###INITIALIZE PROGRAM###
subl  $ST_SIZE_RESERVE, %esp       #Allocate space for our pointers on the stack
movl  %esp, %ebp

### Set standard error code 0
movl $0, %ebx
movl %ebx, ST_EXIT_CODE(%ebp)
    movl ST_ARGV_3(%ebp),%eax  #eax contains now the alternative paramter

1 个答案:

答案 0 :(得分:1)

在“C”中你想要做的是:

if (strcmp(argv[3], "-a") == 0) {
   /* stuff here */
}

由于您在没有C标准库的情况下工作,您必须自己创建strcmp。这并不难,因为它相当于:

int strcmp(const char* str1, const char* str2) {
    while (*str1 && *str1 == *str2) { 
        str1++;
        str2++;
    }
    return *str1 - *str2;
}

或在汇编中:

strcmp:
    push %ebp
    mov %esp, %ebp
    movl 0x8(%ebp), %esi # str1
    movl 0xc(%ebp), %edi # str2
1:
    movb (%esi), %al
    or %al, %al # *str1 zero?
    jz 2f
    movb (%edi), %ah
    cmp %ah, %al # equal to *str2?
    jne 2f
    # move to next character
    inc %esi
    inc %edi
    jmp 1b
2:
    # result is difference between the two characters compared
    movb (%esi), %al
    subb (%edi), %al
    movsx %al, %eax # Sign-extend to 32-bits
    pop %ebp
    ret

当然,如果你实际上没有使用字符串之间的计算差异(它对排序很有用),你可以稍微简化一下程序。

使用它:

    # [snip]
    movl ST_ARGV_3(%ebp),%eax  #eax contains now the alternative paramter

    push %eax      # first argument
    pushl $dasha   # second argument "-a"
    call strcmp    # compare strings
    add $8, %esp   # pop arguments

    cmpl $0, %eax  # Strings equal?
    je strings_are_equal  # Subtitute your own logic here
    jmp strings_are_not_equal # and here..

请注意,这假设您有一个要与数据部分中的位置进行比较的字符串,如:

.section .data 
dasha: .asciz "-a"
相关问题