Read command line arguments in assembly

2.1k Views Asked by At

I'm writing an assembly program in NASM and as part of it I wanna be able to read command line arguments, which in my case could me one of two things, a debug message "-d", or a number represented in Hex, so for example:

`./programName AF -d` 

The thing is when I use pop the first argument off the stack that's not the argc or programName, it's suppose to be a string representing say that HEX number, and I try to process it byte byte eventually ending up with a segfault. Here's my attempt:

main:
push ebp
mov ebp, esp

mov ecx, [ebp +8]      ;argc
mov eax, [ebp + 16]    ; first arg that was put in by the user
dec ecx                ; update num of "real" args

.nextArg:
    cmp ecx, 0
    je .noMoreArgs
    push eax
    call process_arg
    add esp, 4
    dec ecx
    jmp .nextArg
.noMoreArgs:
 ...

process_arg function: (capacity is a variable in memory to indicate capacity in btyes of an allocated stack, debugStr is a string for the purpose of the comparison)

push ebp
mov ebp, esp
mov edx, [ebp+8]                    ; edx points to the argument string

.debug:
    mov bl, byte [edx]                      ; load first byte of debugStr (bl_1 = '-', bl_2 = 'd')
    cmp bl, '-'                        ; cmp char by char
    jnz .stack
    inc edx                            ; get ready for next char
    mov bl, byte [edx]                      ; load second byte of debugStr (bl_1 = '-', bl_2 = 'd')
    cmp bl, 'd'                        ; cmp char by char
    jnz .stack
    mov [debug_mode], dword 1
    jmp end

    .stack:
    mov edx, [ebp+8]                ; ecx points to the argument string
    xor ebx, ebx
    xor eax, eax
    mov ecx, 2
.loop: 
    mov bl, [edx]                   ; get byte pointed to by edx
    cmp bl, '9'                     ; if larger than 9 => digit is a letter (assuming valid input)
    ja .letter                      ; jmp to proceesing a letter digit
    sub bl, '0'
    ja .mul                         
.letter:
    sub bl, 37h
.mul:
    mov edi, 16
    mul edi
    add eax, ebx
    inc edx
    loop .loop

    mov edi, 4
    mul edi
; at this point eax should hold the INT value of stack_size
    mov [capacity], eax             

end:
    pop edx
    pop ecx
    pop ebx
    mov esp, ebp
    pop ebp
    ret

Any idea of what could be the reason? or clarifications about reading cmdline args? As well as the use of lea (load effective address) to this purpose and how it differs from a simple mov?

Thanks in advance.

0

There are 0 best solutions below