From 13d14f7a1f16257df51ec65e4b084ddac581872f Mon Sep 17 00:00:00 2001 From: Kwarde Date: Thu, 10 Jul 2025 12:47:01 +0200 Subject: [PATCH] (Finally) use macros in printf() to shorten code / less repeated code --- src/console.asm | 82 ++++++++++++++++++++----------------------------- 1 file changed, 34 insertions(+), 48 deletions(-) diff --git a/src/console.asm b/src/console.asm index fcac7e0..f420f14 100644 --- a/src/console.asm +++ b/src/console.asm @@ -84,6 +84,31 @@ puts: ; r10* Keeps track of current index of printfBuff ; r11* Keeps track of total characters (return value) printf: + %macro load_arg 1 + cmp rdx, 4 + ja %%fromStack + mov %1, [printfArgs + SIZE_QWORD * rdx] + jmp %%continue + %%fromStack: + mov %1, [rbp + RBP_OFFSET_CALLER + ((rdx-5) * SIZE_QWORD)] + %%continue: + %endmacro + + %macro push_regs 0 + sub rsp, SIZE_QWORD + push rax + push rdx + push rdi + %endmacro + + %macro pop_regs 0 + pop rdi + pop rdx + pop rax + add rsp, SIZE_QWORD + %endmacro + + ; entry: push rbp mov rbp, rsp @@ -155,27 +180,13 @@ printf: ;--- '%c' ---; .rep_c: - cmp rdx, 4 - ja .c_fromStack - mov rsi, [printfArgs + SIZE_QWORD * rdx] - jmp .insertChar - .c_fromStack: - mov rsi, [rbp + RBP_OFFSET_CALLER + ((rdx-5) * SIZE_QWORD)] + load_arg rsi jmp .insertChar ;--- '%i' / '%d' / '%u' ---; .rep_d: - cmp rdx, 4 - ja .d_fromStack - mov rsi, [printfArgs + SIZE_QWORD * rdx] - jmp .checkINTorUINT - .d_fromStack: - mov rsi, [rbp + RBP_OFFSET_CALLER + ((rdx-5) * SIZE_QWORD)] - .checkINTorUINT: - sub rsp, SIZE_QWORD - push rax - push rdx - push rdi + load_arg rsi + push_regs cmp byte [rdi + 1], 'u' je .callUINT2STR mov rdi, rsi @@ -186,22 +197,13 @@ printf: call udec2str .loadConvertedStr: mov rsi, rax - pop rdi - pop rdx - pop rax - add rsp, SIZE_QWORD + pop_regs jmp .insertString ;--- '%x' / '%X' ---; .rep_x: push rdi - cmp rdx, 4 - ja .x_fromStack - mov rcx, [printfArgs + SIZE_QWORD * rdx] - jmp .convertHex - .x_fromStack: - mov rcx, [rbp + RBP_OFFSET_CALLER + ((rdx-5) * SIZE_QWORD)] - .convertHex: + load_arg rcx xor rsi, rsi mov r8, 1 cmp byte [rdi + 1], 'X' @@ -221,33 +223,17 @@ printf: ;--- '%b' ---; .rep_b: cmp rdx, 4 - ja .b_fromStack - mov rsi, [printfArgs + SIZE_QWORD * rdx] - jmp .convertBin - .b_fromStack: - mov rsi, [rbp + RBP_OFFSET_CALLER + ((rdx-5) * SIZE_QWORD)] - .convertBin: - sub rsp, SIZE_QWORD - push rax - push rdx - push rdi + load_arg rsi + push_regs mov rdi, rsi call bin2str mov rsi, rax - pop rdi - pop rdx - pop rax - add rsp, SIZE_QWORD + pop_regs jmp .insertString ;--- '%s' ---; .rep_s: - cmp rdx, 4 - ja .s_fromStack - mov rsi, [printfArgs + SIZE_QWORD * rdx] - jmp .insertString - .s_fromStack: - mov rsi, [rbp + RBP_OFFSET_CALLER + ((rdx-5) * SIZE_QWORD)] + load_arg rsi ;--- Insert string to buffer ---; .insertString: