Problems with accessing command line arguments in

2019-03-06 15:14发布

问题:

I have a basic asm program that checks if a string is a digit. I was adding in code to read from command line arguements, put it keeps seg faulting.

if what I have read is right, this should get the amount of arguments passed to the program, which should be stored in 0(%ebp). What am i doing wrong?

The entirity of the code can be found here: http://pastebin.com/kGV2Mxx4 The problem is the first 3-5 lines of _start.

upon Looking at lscpu's output, I have an i868 cpu. Although, it says it can operate in 32-bit and 64-bit. I am running 32 bit linux (Arch linux x86)

I fixed the issue. I did 2 pop's, one to bypass the programs name, the next to get the first argument. the updated code can be found here: http://pastebin.com/xewyeHYf

Can someone please tell me why I could not just do the following:

pushl 8(%ebp)

or

movl 8(%ebp), %eax

回答1:

You could write this:

_start:
b1: movl    0(%ebp), %eax
    cmpl    $1, %eax
    je      load_msg
b2:    pushl    8(%ebp)
b4:    call    check

To understand why your previous attempts didn't work, draw stack diagrams.



回答2:

Here is a little tutorial I wrote on the subject: NASM - Linux Getting command line parameters



回答3:

Compile a small C program that does something like what you want to do, and compile it to assembly language to find out exactly how to access arguments. The x86_32 code doesn't look at all like any of the above, BTW:

int main(int argc, char *argv[])
{
  return argv[1][0];
}

gives (yes, some is superfluous stack bookkeeping, but anyway):

    .file   "tst.c"
    .text
    .globl  main
    .type   main, @function
main:
.LFB0:
    .cfi_startproc
    pushl   %ebp
    .cfi_def_cfa_offset 8
    .cfi_offset 5, -8
    movl    %esp, %ebp
    .cfi_def_cfa_register 5
    movl    12(%ebp), %eax
    addl    $4, %eax
    movl    (%eax), %eax
    movzbl  (%eax), %eax
    movsbl  %al, %eax
    popl    %ebp
    .cfi_restore 5
    .cfi_def_cfa 4, 4
    ret
    .cfi_endproc
.LFE0:
    .size   main, .-main
    .ident  "GCC: (GNU) 4.7.2 20121109 (Red Hat 4.7.2-8)"
    .section    .note.GNU-stack,"",@progbits