打印命令行参数x86程序集

时间:2019-01-20 23:38:24

标签: linux assembly nasm

首先,我是汇编语言的新手,但是在c ++中有相当不错的背景。我的问题源于我在使用汇编程序的命令行参数上关注的教程。

在程序运行时,它会根据教程执行所有操作,该教程显示程序输入列表:     URL.createObjectURL()

关注的是何时提供astrisk作为参数:     ./asm1 arg1 arg2 arg3

  

它可以在CWD上有效地执行 / usr / bin / ls

我的问题是如何避免这种情况,以及有关实施此程序的更好方法的任何建议。

  

已替换:

./asm1 *
  

使用:

; the loop
        cmp ecx, eax        ; if ecx not equal to eax
        jne begin_for_loop  ; jmp to loop, else exit
  

我发现了一个更大的问题,程序将ENV变量打印到屏幕上。

这是下面的原始程序:

; the loop
         cmp ecx, eax        ; if ecx not equal to eax
         jmp begin_for_loop  ; jmp to loop, else exit

预期输出:

; FOR LOOP: Print commandline arguments> an equivalent program to 
this in assembly
SECTION .data

    argv db "Arguments = %s",10,0
    argc db "Argument Count = %d",10,0

SECTION .text
; allow access to printf
extern printf
; make main_function available externally
global main


main:    ; int main (int argc, char* argv[])
    push ebp
    mov ebp,esp
    sub esp, 10

    mov eax, DWORD [ebp + 8]    ; points to argc
    mov ebx, DWORD [ebp + 12]   ; points to argv
    mov ecx, 0      ; mov ZERO to count register

begin_for_loop:
    ; always preserve values prior to external function calls
    ; external function calls may modify values you placed in registers
    push ebx    ; preserve ebx; holds argument address
    push eax    ; preserve eax; holds number of arguments
    push ecx    ; preserve ecx; holds the counter

    ; call printf
    push DWORD [ebx]
    push argv
    call printf
    add esp, 8  ; clean up the stack

    ; always restore in backwards order
    pop ecx     ; restore counter
    pop eax     ; restore number of arguments
    pop ebx     ; restore argument address

    inc ecx     ; increase our counter by 1
    add ebx, 4  ; move to next argument in the array

    ; the loop
    cmp ecx, eax        ; if ecx not equal to eax
    jne begin_for_loop  ; jmp to loop, else exit


    mov esp,ebp
    pop ebp
    ret

可疑的输出:

$ ./asm5 me you them us
Arguments = ./asm5
Arguments = me
Arguments = you
Arguments = them
Arguments = us

1 个答案:

答案 0 :(得分:4)

在POSIX系统上,如果您从外壳启动程序,则该外壳将执行所谓的globing,展开*并将其替换为匹配的文件;结果将用作调用程序的参数。

您无法采取任何措施阻止它在您的程序中运行,您看到的参数确实是从外壳程序获得的参数(IOW,它们是已传递给exec的参数)。

如果要从外壳程序启动文本*到程序时,必须将其引号。

./asm5 me you them us "*"

当然,如果其他程序启动您的程序将参数直接传递给exec,而没有Shell的阻碍,则不会发生任何事情。


  
    

已替换:

  
; the loop
         cmp ecx, eax        ; if ecx not equal to eax
         jne begin_for_loop  ; jmp to loop, else exit
     
    

使用:

  
; the loop
         cmp ecx, eax        ; if ecx not equal to eax
         jmp begin_for_loop  ; jmp to loop, else exit
     
    

我发现了一个更大的问题,程序将ENV变量打印到屏幕上。

  

这是因为您忽略了终止argv参数列表的NULL,而您将继续阅读下一个内容。在您的情况下,这恰好是环境内存块。