Skip to content

Instantly share code, notes, and snippets.

@asamy
Last active April 1, 2025 03:39
Show Gist options
  • Save asamy/6344483 to your computer and use it in GitHub Desktop.
Save asamy/6344483 to your computer and use it in GitHub Desktop.
Retrieving command-line arguments in x86 assembly.
/*
Copyright (C) 2013 Ahmed Samy <[email protected]>, MIT.
Retrive command line arguments and output them to stdout.
Compile:
gcc cmd.S
Run:
./a.out 1 2 3
Should output:
There are 4 params:
./a.out
1
2
3
*/
.data
output:
.asciz "There are %d params:\n"
.text
.globl main
main:
movl 4(%esp), %ecx /* Get argument count. */
pushl %ecx
pushl $output
call printf
addl $4, %esp /* remove output */
/* ECX was corrupted by the printf call,
pop it off the stack so that we get it's original
value. */
popl %ecx
movl 8(%esp), %ebp /* Get argv. */
pr_arg:
pushl %ecx
pushl (%ebp)
call puts
addl $4, %esp /* remove current argument. */
addl $4, %ebp
popl %ecx
loop pr_arg
ret
@nelani
Copy link

nelani commented Nov 13, 2017

I tried this and got errors for the push and pop. Any ideas why?

@futilityteam
Copy link

@nelani It's probably because you are compiling it for 64 bit. Those pushes and pulls only work in 32 bit apps.

@realyukii
Copy link

realyukii commented Apr 1, 2025

is this applied on Windows program? what if I didn't use main? and using my own _start instead?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment