Page 1 of 1

How do you make use of command-line arguments? (asm/linux)

Posted: Fri Dec 07, 2007 11:55 am
by novenary
Hi everyone. I'm in the process of learning asm for x86 on linux, using gas. I'm experimenting with what I know and I'm curious about how I could say, run ./example [argument] and have the program work with that argument.

I tried experimenting to see if the argument is passed to a register, and also in the previous stack frame but I haven't had any luck yet. Will this be more complex than I think it is?

Code: Select all

#PURPOSE:	Simple program that exits and returns a value to the kernel

#VARIABLES:
#		%eax holds the system call number
#		%ebx holds the return status
#
.section .data
.section .text

.globl _start
_start:

movl 8(%esp), %ebx          #copy data from above stack frame into %ebx

movl $1, %eax	                 #prepare kernel exit call
int $0x80                             #exit
After running I check with echo $? to see the return value. An argument passed while running this does change the return, but not with my value.

I'm just experimenting and having fun, so if I'm doing anything silly, keep that in mind :)

Posted: Fri Dec 07, 2007 2:57 pm
by Alboin

Posted: Sat Dec 08, 2007 10:51 am
by novenary
Thanks for that link Alboin. I found some source in assembly on that page that does what I'm looking for. It's just going to take me some time to digest it, but not too long.

Code: Select all

/* args.s */

.text
.globl _start
_start:
	popl	%ecx		// argc
lewp:
	popl	%ecx		// argv
	test 	%ecx,%ecx
	jz	exit

	movl	%ecx,%ebx
	xorl	%edx,%edx
strlen:
	movb	(%ebx),%al
	inc	%edx
	inc	%ebx
	test	%al,%al
	jnz	strlen
	movb	$10,-1(%ebx)

// 	write(1,argv[i],strlen(argv[i]));
	movl	$SYS_write,%eax
	movl	$STDOUT,%ebx
	int	$0x80

	jmp	lewp
exit:
	movl	$SYS_exit,%eax
	xorl	%ebx,%ebx
	int 	$0x80
		
	ret

Posted: Sat Dec 08, 2007 2:57 pm
by Dex
To me this will give you the name of the program.
As i make it
pop ecx ; Number of arguments
pop ecx ; Get first argument (the program name)
pop ecx ; Get second argument (you may want this one)