.global reverseString n2rev = str + 4 # n2rev is pushed first, str is a pointer, # it needs 4 bytes str = ret_addr + 4 # return address needs four bytes ret_addr = oldbp + 4 # oldbp needs four bytes oldbp = 0 # ebp points to oldbp bufferlen = 32 buffer = oldbp - bufferlen # buffer is allocated 32 chars reverseString: pushl %ebp movl %esp,%ebp addl $buffer,%esp # to reserve space for local var pushl %eax pushl %ebx pushl %ecx pushl %edx # copy from str (pointer) to buffer (array) up to min(n2rev, bufferlen) characters # retrieve n2rev to a register %eax movl n2rev(%ebp), %eax cmpl $bufferlen, %eax jna n2rev_is_fine # n2rev is above bufferlen movl $bufferlen, %eax n2rev_is_fine: # eax is the max. number of characters to copy and reverse # copy from str to buffer # first load str into a register %ebx (so I can use indirect later) movl str(%ebp), %ebx # use ecx as destination pointer movl $buffer, %ecx addl %ebp, %ecx # ecx is ebp + buffer pushl %ecx # save start address of buffer # the other instruction to replace the prev. two instructions is # lea buffer(%ebp), %ecx but this is confusing copy_another_byte: cmpl $0,%eax jz done_copying cmpb $0,(%ebx) # check for null char jz done_copying # now we can copy movb (%ebx), %dl movb %dl,(%ecx) subl $1,%eax addl $1,%ebx addl $1,%ecx jmp copy_another_byte done_copying: # ready to reverse # TODO: finish reversal logic on Monday popl %eax pushl %ecx # pointing to the end pushl %eax # pointing to the beginning # eax points to the first byte of buffer # ecx points to the last byte of buffer subl $1,%ecx reverse_another_char: cmpl %eax,%ecx jna done_reversing # when ecx <= eax, exit loop # now swap (%eax) with (%ecx) movb (%eax),%bl movb (%ecx),%bh movb %bl,(%ecx) movb %bh,(%eax) addl $1,%eax subl $1,%ecx jmp reverse_another_char done_reversing: # now it is time to print it out popl %ecx popl %edx subl %ecx,%edx movl $4,%eax movl $1,%ebx int $0x80 popl %edx popl %ecx popl %ebx popl %eax subl $buffer,%esp # to deallocate space for local var # this is what compilers do: movl %ebp,%esp popl %ebp ret # this is a program to illustrate how to pass parameters on the stack