From f7a0196764ccb0ba4f2b7ea4078a5d1d9aa154b4 Mon Sep 17 00:00:00 2001 From: Rodrigo Tobar Date: Sun, 3 Oct 2021 15:40:27 +0800 Subject: [PATCH] Strace: Move output formatting to separate function Moving the formatting of strace's output into a separate function will allow us to introduce more complexity into the formatting logic without touching the main body of the program. The new function uses a switch statement to select how to format the arguments and result depending on the syscall. At this point we only include the default formatting, where the registers are simply dumped, but later on we can add specializations for each system call we want to support. --- Userland/Utilities/strace.cpp | 49 +++++++++++++++++++++++++---------- 1 file changed, 35 insertions(+), 14 deletions(-) diff --git a/Userland/Utilities/strace.cpp b/Userland/Utilities/strace.cpp index 82b2ed9ecf..a136533bc3 100644 --- a/Userland/Utilities/strace.cpp +++ b/Userland/Utilities/strace.cpp @@ -20,6 +20,12 @@ static int g_pid = -1; +#if ARCH(I386) +using syscall_arg_t = u32; +#else +using syscall_arg_t = u64; +#endif + static void handle_sigint(int) { if (g_pid == -1) @@ -30,6 +36,26 @@ static void handle_sigint(int) } } +static String format_syscall(syscall_arg_t syscall_index, syscall_arg_t arg1, syscall_arg_t arg2, syscall_arg_t arg3, syscall_arg_t res) +{ + auto syscall_function = (Syscall::Function)syscall_index; + StringBuilder builder; + builder.append(Syscall::to_string(syscall_function)); + builder.append('('); + + switch (syscall_function) { + default: + builder.appendff("{:#08x}, {:#08x}, {:#08x})\t={}", + arg1, + arg2, + arg3, + res); + } + + builder.append('\n'); + return builder.to_string(); +} + int main(int argc, char** argv) { if (pledge("stdio wpath cpath proc exec ptrace sigaction", nullptr) < 0) { @@ -129,15 +155,15 @@ int main(int argc, char** argv) return 1; } #if ARCH(I386) - u32 syscall_index = regs.eax; - u32 arg1 = regs.edx; - u32 arg2 = regs.ecx; - u32 arg3 = regs.ebx; + syscall_arg_t syscall_index = regs.eax; + syscall_arg_t arg1 = regs.edx; + syscall_arg_t arg2 = regs.ecx; + syscall_arg_t arg3 = regs.ebx; #else - u64 syscall_index = regs.rax; - u64 arg1 = regs.rdx; - u64 arg2 = regs.rcx; - u64 arg3 = regs.rbx; + syscall_arg_t syscall_index = regs.rax; + syscall_arg_t arg1 = regs.rdx; + syscall_arg_t arg2 = regs.rcx; + syscall_arg_t arg3 = regs.rbx; #endif if (ptrace(PT_SYSCALL, g_pid, 0, 0) == -1) { @@ -160,12 +186,7 @@ int main(int argc, char** argv) u64 res = regs.rax; #endif - auto string = String::formatted("{}({:#08x}, {:#08x}, {:#08x})\t={}\n", - Syscall::to_string((Syscall::Function)syscall_index), - arg1, - arg2, - arg3, - res); + auto string = format_syscall(syscall_index, arg1, arg2, arg3, res); if (!trace_file->write(string)) { warnln("write: {}", trace_file->error_string());