Last active
December 24, 2020 08:49
-
-
Save seisvelas/0716d200884cb81856cb5f2b4bfefb99 to your computer and use it in GitHub Desktop.
Solution to the bus toy problem Khety created for me
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
global busString | |
extern sprintf | |
section .data | |
busStringFormat: db "%ld more people are allowed onto the bus.", 10, 0 | |
busOutOfSpace: db "No more people can fit on the bus.", 10, 0 | |
section .bss | |
output_buff: resb 5000 | |
section .text | |
busCount: | |
xor rax, rax | |
cmp rdi, rsi | |
jg no_more_room | |
sub rsi, rdi | |
mov rax, rsi | |
jmp return | |
no_more_room: | |
xor rax, rax | |
return: | |
ret | |
busString: | |
sub rsp, 8 | |
call busCount | |
cmp rax, 0 | |
je no_more_room_return | |
; diff now in rax | |
mov r8, rax | |
xor eax, eax | |
mov rdi, output_buff | |
mov rsi, busStringFormat | |
mov rdx, r8 | |
precall: | |
call sprintf | |
postcall: | |
mov rax, output_buff | |
add rsp, 8 | |
ret | |
no_more_room_return: | |
mov rax, busOutOfSpace | |
add rsp, 8 | |
ret |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdint.h> | |
char* busString(int64_t, int64_t); | |
int main(void) { | |
printf("%s", busString(50, 60)); | |
printf("%s", busString(50, 49)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Finally works!
I had gotten quite stuck with a segfault because I was not realigning the stack to 16 bits, so I asked this question on StackOverflow:
https://stackoverflow.com/questions/65435315/calling-sprintf-in-nasm-x86-64-gives-segmentation-fault
Peter Cordes (the legend himself) helped me and now it works. Tbh I still don't deeply understand stack alignment or why it matters, so I guess that's something I'll have to look into.