Blogging about our lives online.


Assembly Language - Command line parameters

I ran into a problem with the way that command line parameters are passed in Assembly Language. The book I'm working through has a couple example programs illustrating how to access the command line arguments and none of these examples worked on my system. The simple solution was that, at some point between this book being written and me reading it, this convention had changed. Instead of the stack looking like it does in the book, with all the command line arguments on the stack, we have the number of parameters first and then a pointer to a pointer to all the parameters in null terminated strings.

This is how it looks in the old style:
number: 3
*p1: program name
*p2: param1
*p2: param2

And this is how it looks in the new style:
number: 3
*p: *params
*params: param1, param2, ...

I should have guessed this from the C calling convention **args, but it took a fair bit of digging with GDB to analyze what exactly was going on with the stack. So, the end result: A program to print all the command line arguments:

.section .data
    .asciz "parameter: %s\n"
.section .bss
.section .text
.globl main

    movl    (%esp), %ebx
    movl    4(%esp), %ecx      # Num parameters
    movl    8(%esp), %ebx      # This is a pointer to the string pointer
    movl    (%ebx), %edi       # This should be the string pointer
        pushl   %ecx
        pushl   %edi
        pushl   $output
        call    printf
        addl    $8, %esp
        movl    $0x255, %ecx
        movb    $0, %al 
        repne   scasb
        popl    %ecx
        loop    loopargs
    movl $1, %eax
    movl $0, %ebx
    int $0x80

No comments:

Post a Comment