Skip to content

Instantly share code, notes, and snippets.

@seisvelas
Last active December 24, 2020 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seisvelas/0716d200884cb81856cb5f2b4bfefb99 to your computer and use it in GitHub Desktop.
Save seisvelas/0716d200884cb81856cb5f2b4bfefb99 to your computer and use it in GitHub Desktop.
Solution to the bus toy problem Khety created for me
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
#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;
}
@seisvelas
Copy link
Author

Finally works!

alex@home:~/Code/Khety$ nasm -felf64 bus.s && gcc bus.c bus.o -no-pie && ./a.out 
10 more people are allowed onto the bus.
No more people can fit on the bus.

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.

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