Stack Calculator
Part of the Functions, Stack and Strings section of Coddy's Assembly journey. Lesson 32 of 33.
Challenge
HardA postfix expression writes the operator after its two numbers: 3 4 + 2 * means (3 + 4) * 2. solve receives the address of such an expression in rdi, ending with a zero byte: single digits 0 to 9, the operators +, - and *, and one space between items. Push each number; on an operator, pop two numbers, apply it (the first number popped is the right side) and push the result. The input is always valid: return the last value on the stack in rax, which can be negative.
Example: for the input 3 4 + 2 * the program prints 14.
Write your code in solution.asm. The locked main.asm reads one line of text, calls solve and prints the number in rax.
Try it yourself
bits 64
section .data
changed_rbx db 'solve changed rbx', 10
changed_rbp db 'solve changed rbp', 10
changed_r12 db 'solve changed r12', 10
changed_r13 db 'solve changed r13', 10
changed_r14 db 'solve changed r14', 10
changed_r15 db 'solve changed r15', 10
section .bss
input_buffer resb 257
text_buffer resb 256
output_buffer resb 32
section .text
global _start
extern solve
_start:
xor eax, eax
xor edi, edi
mov rsi, input_buffer
mov edx, 255
syscall
test rax, rax
jg .trim
xor eax, eax
.trim:
test rax, rax
jz .ended
movzx edx, byte [input_buffer + rax - 1]
cmp dl, 10
je .drop
cmp dl, 13
jne .ended
.drop:
dec rax
jmp .trim
.ended:
mov byte [input_buffer + rax], 0
mov rbx, 0x1111111111111111
mov rbp, 0x2222222222222222
mov r12, 0x3333333333333333
mov r13, 0x4444444444444444
mov r14, 0x5555555555555555
mov r15, 0x6666666666666666
lea rdi, [input_buffer]
lea rsi, [text_buffer]
xor eax, eax
call solve
mov rdx, 0x1111111111111111
lea rsi, [changed_rbx]
cmp rbx, rdx
jne .changed
mov rdx, 0x2222222222222222
lea rsi, [changed_rbp]
cmp rbp, rdx
jne .changed
mov rdx, 0x3333333333333333
lea rsi, [changed_r12]
cmp r12, rdx
jne .changed
mov rdx, 0x4444444444444444
lea rsi, [changed_r13]
cmp r13, rdx
jne .changed
mov rdx, 0x5555555555555555
lea rsi, [changed_r14]
cmp r14, rdx
jne .changed
mov rdx, 0x6666666666666666
lea rsi, [changed_r15]
cmp r15, rdx
jne .changed
lea rsi, [output_buffer + 31]
mov byte [rsi], 10
mov ecx, 1
xor r8d, r8d
test rax, rax
jns .positive
mov r8d, 1
neg rax
.positive:
mov r9d, 10
.convert:
xor edx, edx
div r9
add dl, '0'
dec rsi
mov [rsi], dl
inc ecx
test rax, rax
jnz .convert
test r8d, r8d
jz .write
dec rsi
mov byte [rsi], '-'
inc ecx
.write:
mov edx, ecx
mov eax, 1
mov edi, 1
syscall
.exit:
mov eax, 60
xor edi, edi
syscall
.changed:
mov eax, 1
mov edi, 1
mov edx, 18
syscall
jmp .exitAll lessons in Functions, Stack and Strings
4Stack Frames and Recursion
Local VariablesFrames with RBPRecursionTwo Recursive CallsRecap: Digit Sum3The Calling Convention
Arguments in RegistersReturn ValuesCaller-Saved RegistersCallee-Saved RegistersRecap: Scoreboard6Project: Word Counter
The Read SyscallCount the CharactersPractice on your own: Assembly playground