Skip to content

Instantly share code, notes, and snippets.

@dstein64 dstein64/printenv.s
Created Oct 29, 2017

Embed
What would you like to do?
/*** printenv.s ***/
// Description
// printenv - print the environment to stdout
// Synopsis
// printenv
// Build
// $ as --32 -o printenv.o printenv.s
// $ ld -m elf_i386 -o printenv printenv.o
.section .text
# ************************************
# * print macro
# * Caller is responsible for setting
# * %ecx and %edx, and saving %eax and
# * %ebx if necessary.
# ************************************
.macro print
movl $4, %eax
movl $1, %ebx
int $0x80
.endm
# ************************************
# * int strlen(char* str);
# * Returns the length of a string.
# ************************************
.type strlen, @function
strlen:
pushl %ebp
movl %esp, %ebp
movl $0, %eax # Index
movl 8(%ebp), %ecx # Address of str
strlen_loop:
movb (%ecx,%eax,1), %dl # Current char
cmpb $0, %dl
je strlen_end
incl %eax
jmp strlen_loop
strlen_end:
movl %ebp, %esp
popl %ebp
ret
.section .rodata
newline_char:
.ascii "\n"
.section .text
# ************************************
# * printenv
# * Prints the environment to stdout.
# ************************************
.globl _start
_start:
movl %esp, %ebp
# Local variables (offset from %ebp)
.equ index, -4 # Stack index being operated on
.equ address, -8 # Current env var address
.equ length, -12 # Current env var length
subl $12, %esp
# Start at index argc+1 (this skips the argument vector)
movl $0, index(%ebp)
movl (%ebp), %eax # argc
incl %eax
addl %eax, index(%ebp)
printenv_loop:
# Set address local variable
movl index(%ebp), %ecx
movl 4(%ebp, %ecx, 4), %eax
movl %eax, address(%ebp)
# Check if we're done (reached a NULL pointer)
cmpl $0, address(%ebp)
je printenv_loop_end
# Calculate length of string
pushl address(%ebp)
call strlen
addl $4, %esp
# Set length local variable
movl %eax, length(%ebp)
# Print current env var
movl address(%ebp), %ecx
movl length(%ebp), %edx
print
# Print newline char
movl $newline_char, %ecx
movl $1, %edx
print
incl index(%ebp)
jmp printenv_loop
printenv_loop_end:
# Exit
movl $1, %eax
movl $0, %ebx
int $0x80
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.