(Finally) use macros in printf() to shorten code / less repeated code

This commit is contained in:
2025-07-10 12:47:01 +02:00
parent 902d962068
commit 13d14f7a1f

View File

@@ -84,6 +84,31 @@ puts:
; r10* Keeps track of current index of printfBuff ; r10* Keeps track of current index of printfBuff
; r11* Keeps track of total characters (return value) ; r11* Keeps track of total characters (return value)
printf: 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 push rbp
mov rbp, rsp mov rbp, rsp
@@ -155,27 +180,13 @@ printf:
;--- '%c' ---; ;--- '%c' ---;
.rep_c: .rep_c:
cmp rdx, 4 load_arg rsi
ja .c_fromStack
mov rsi, [printfArgs + SIZE_QWORD * rdx]
jmp .insertChar
.c_fromStack:
mov rsi, [rbp + RBP_OFFSET_CALLER + ((rdx-5) * SIZE_QWORD)]
jmp .insertChar jmp .insertChar
;--- '%i' / '%d' / '%u' ---; ;--- '%i' / '%d' / '%u' ---;
.rep_d: .rep_d:
cmp rdx, 4 load_arg rsi
ja .d_fromStack push_regs
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
cmp byte [rdi + 1], 'u' cmp byte [rdi + 1], 'u'
je .callUINT2STR je .callUINT2STR
mov rdi, rsi mov rdi, rsi
@@ -186,22 +197,13 @@ printf:
call udec2str call udec2str
.loadConvertedStr: .loadConvertedStr:
mov rsi, rax mov rsi, rax
pop rdi pop_regs
pop rdx
pop rax
add rsp, SIZE_QWORD
jmp .insertString jmp .insertString
;--- '%x' / '%X' ---; ;--- '%x' / '%X' ---;
.rep_x: .rep_x:
push rdi push rdi
cmp rdx, 4 load_arg rcx
ja .x_fromStack
mov rcx, [printfArgs + SIZE_QWORD * rdx]
jmp .convertHex
.x_fromStack:
mov rcx, [rbp + RBP_OFFSET_CALLER + ((rdx-5) * SIZE_QWORD)]
.convertHex:
xor rsi, rsi xor rsi, rsi
mov r8, 1 mov r8, 1
cmp byte [rdi + 1], 'X' cmp byte [rdi + 1], 'X'
@@ -221,33 +223,17 @@ printf:
;--- '%b' ---; ;--- '%b' ---;
.rep_b: .rep_b:
cmp rdx, 4 cmp rdx, 4
ja .b_fromStack load_arg rsi
mov rsi, [printfArgs + SIZE_QWORD * rdx] push_regs
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
mov rdi, rsi mov rdi, rsi
call bin2str call bin2str
mov rsi, rax mov rsi, rax
pop rdi pop_regs
pop rdx
pop rax
add rsp, SIZE_QWORD
jmp .insertString jmp .insertString
;--- '%s' ---; ;--- '%s' ---;
.rep_s: .rep_s:
cmp rdx, 4 load_arg rsi
ja .s_fromStack
mov rsi, [printfArgs + SIZE_QWORD * rdx]
jmp .insertString
.s_fromStack:
mov rsi, [rbp + RBP_OFFSET_CALLER + ((rdx-5) * SIZE_QWORD)]
;--- Insert string to buffer ---; ;--- Insert string to buffer ---;
.insertString: .insertString: