jaybee
jaybee

Reputation: 1925

treating command-line args as integers in x86 AT&T Assembly

This (Linux, AT&T, Intel) x86 program is meant to read in three arguments and store the biggest in %ebx as the exist status. When I pop the arguments into registers the resulting values seems to be bytes. How do I get the int value?

[edit -- thanks to harold's comment below I think the question is how do I use atoi to get the int value of the args.]

.section .text

.globl _start           

_start:
popl    %edi        # Get the number of arguments
popl    %eax        # Get the program name
popl    %ebx        # Get the first actual argument 
movl    (%ebx), %ebx    # get the actual value into the register (?) 
popl    %ecx        # ;
movl    (%ecx), %ecx
popl    %edx        #
movl    (%edx), %edx

bxcx:   
cmpl    %ebx,%ecx
jle     bxdx
movl    %ecx,%ebx
bxdx:
cmpl    %ebx,%edx
jle end
movl    %edx,%ebx

end:
movl    $1,%eax         
int $0x80           

Upvotes: 1

Views: 1623

Answers (1)

laindir
laindir

Reputation: 1710

To be able to call atoi, you'll need to link against libc. e.g.:

ld -lc foo.o

To actually make the call, you'll need to follow the cdecl calling convention:

  1. Arguments to functions are passed on the stack with the leftmost argument being pushed last.
  2. The return value of the function will be placed in the accumulator (%eax in this case).
  3. Registers %ebp, %esi, %edi, and %ebx are preserved across calls, so you can use them for temporary storage.
  4. Any other needed registers must be saved by the calling code (in the callee-saved registers above, on the stack before your arguments, or elsewhere in memory).

The signature of atoi is

int atoi(const char *nptr);

so to get the integer value of the first command line argument, we could do

.section .text

.globl _start           

_start:
popl    %edi        # Get the number of arguments
popl    %eax        # Get the program name
call    atoi        # Try to read the first argument as an integer and clobber %eax with the value

Upvotes: 3

Related Questions