diff --git a/build.sh b/build.sh index a18814f..48af5cf 100644 --- a/build.sh +++ b/build.sh @@ -1,3 +1,11 @@ +assemble () { + FILE="$1" + PROGRAM_NAME="$2" + + echo "Assembling $PROGRAM_NAME" + nasm -g -F dwarf -f elf64 "$FILE" -o "./target/$PROGRAM_NAME.o" || return +} + build () { FILE="$1" PROGRAM_NAME=$(basename "$FILE" ".asm") @@ -7,8 +15,16 @@ build () { return fi - echo "Building $PROGRAM_NAME" - nasm -g -F dwarf -f elf64 "$FILE" -o "./target/$PROGRAM_NAME.o" && ld.lld "./target/$PROGRAM_NAME.o" -o "./target/$PROGRAM_NAME" + + if [ "$PROGRAM_NAME" = "common" ]; then + # common does not need to be linked into an executable + return + fi + + assemble "$FILE" "$PROGRAM_NAME" + + echo "Linking $PROGRAM_NAME" + ld.lld "./target/$PROGRAM_NAME.o" "./target/common.o" -o "./target/$PROGRAM_NAME" } @@ -21,6 +37,9 @@ if [ ! -d ./target ]; then mkdir ./target fi + +assemble "src/common.asm" "common" + if [ "$#" -eq 0 ]; then for FILE in ./src/*.asm ; do build "$FILE" diff --git a/src/itoa.asm b/src/common.asm similarity index 79% rename from src/itoa.asm rename to src/common.asm index ef31e93..f913ff9 100644 --- a/src/itoa.asm +++ b/src/common.asm @@ -1,37 +1,4 @@ - global _start - -NUMBER EQU 0 - - section .data -buffer: times 8 db 0 - - - section .text -_start: - mov rax, NUMBER - mov rbx, buffer - call itoa - cmp rax, 0 - jnz error - -write_buffer: - mov rax, 1 ; write - mov rdi, 1 ; stdout - mov rsi, buffer - mov rdx, rbx ; the length - syscall - -graceful_exit: - xor rdi, rdi - jmp exit - -error: - mov rdi, 1 -exit: - mov rax, 60 - syscall - - + global itoa ; itoa - converts an unsigned integer into its ascii representation ; inputs: @@ -41,10 +8,12 @@ exit: ; rax - 0: success, 1: error ; rbx - the length -MAX_SIZE EQU 100000 +MAX_SIZE EQU 1000000000 START_DIVISOR EQU MAX_SIZE / 10 ASCII_NUM EQU 48 + section .text + itoa: ; r12: whether we are in the leading zeroes (bool) ; r11: buffer start diff --git a/src/wc.asm b/src/wc.asm new file mode 100644 index 0000000..bc3e77e --- /dev/null +++ b/src/wc.asm @@ -0,0 +1,21 @@ + extern itoa + global _start + + section .data +itoa_buf: times 100 db 0 + + section .text +_start: + mov rax, 45354 + mov rbx, itoa_buf + call itoa + + mov rdx, rbx + mov rax, 1 + mov rdi, 1 + mov rsi, itoa_buf + syscall + + mov rax, 60 + xor rdi, rdi + syscall