summaryrefslogtreecommitdiff
path: root/Userland/Utilities/functrace.cpp
blob: 25e02a7ddc624ba556aa451e16d6ea13ec63c614 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
/*
 * Copyright (c) 2020, Itamar S. <itamar8910@gmail.com>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <AK/Assertions.h>
#include <AK/HashMap.h>
#include <AK/NonnullOwnPtr.h>
#include <AK/StringBuilder.h>
#include <LibC/sys/arch/i386/regs.h>
#include <LibCore/ArgsParser.h>
#include <LibCore/File.h>
#include <LibCore/System.h>
#include <LibDebug/DebugSession.h>
#include <LibELF/Image.h>
#include <LibMain/Main.h>
#include <LibX86/Disassembler.h>
#include <LibX86/Instruction.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <syscall.h>
#include <unistd.h>

static OwnPtr<Debug::DebugSession> g_debug_session;
static bool g_should_output_color = false;

static void handle_sigint(int)
{
    outln("Debugger: SIGINT");

    // The destructor of DebugSession takes care of detaching
    g_debug_session = nullptr;
}

static void print_function_call(String function_name, size_t depth)
{
    for (size_t i = 0; i < depth; ++i) {
        out("  ");
    }
    outln("=> {}", function_name);
}

static void print_syscall(PtraceRegisters& regs, size_t depth)
{
    for (size_t i = 0; i < depth; ++i) {
        out("  ");
    }
    StringView begin_color = g_should_output_color ? "\033[34;1m"sv : ""sv;
    StringView end_color = g_should_output_color ? "\033[0m"sv : ""sv;
#if ARCH(I386)
    outln("=> {}SC_{}({:#x}, {:#x}, {:#x}){}",
        begin_color,
        Syscall::to_string((Syscall::Function)regs.eax),
        regs.edx,
        regs.ecx,
        regs.ebx,
        end_color);
#else
    outln("=> {}SC_{}({:#x}, {:#x}, {:#x}){}",
        begin_color,
        Syscall::to_string((Syscall::Function)regs.rax),
        regs.rdx,
        regs.rcx,
        regs.rbx,
        end_color);
#endif
}

static NonnullOwnPtr<HashMap<void*, X86::Instruction>> instrument_code()
{
    auto instrumented = make<HashMap<void*, X86::Instruction>>();
    g_debug_session->for_each_loaded_library([&](const Debug::LoadedLibrary& lib) {
        lib.debug_info->elf().for_each_section_of_type(SHT_PROGBITS, [&](const ELF::Image::Section& section) {
            if (section.name() != ".text")
                return IterationDecision::Continue;

            X86::SimpleInstructionStream stream((const u8*)((uintptr_t)lib.file->data() + section.offset()), section.size());
            X86::Disassembler disassembler(stream);
            for (;;) {
                auto offset = stream.offset();
                void* instruction_address = (void*)(section.address() + offset + lib.base_address);
                auto insn = disassembler.next();
                if (!insn.has_value())
                    break;
                if (insn.value().mnemonic() == "RET" || insn.value().mnemonic() == "CALL") {
                    g_debug_session->insert_breakpoint(instruction_address);
                    instrumented->set(instruction_address, insn.value());
                }
            }
            return IterationDecision::Continue;
        });
        return IterationDecision::Continue;
    });
    return instrumented;
}

ErrorOr<int> serenity_main(Main::Arguments arguments)
{
    TRY(Core::System::pledge("stdio proc exec rpath sigaction ptrace"));

    if (isatty(STDOUT_FILENO))
        g_should_output_color = true;

    StringView command;
    Core::ArgsParser args_parser;
    args_parser.add_positional_argument(command,
        "The program to be traced, along with its arguments",
        "program", Core::ArgsParser::Required::Yes);
    args_parser.parse(arguments);

    auto result = Debug::DebugSession::exec_and_attach(command);
    if (!result) {
        warnln("Failed to start debugging session for: \"{}\"", command);
        exit(1);
    }
    g_debug_session = result.release_nonnull();

    auto instrumented = instrument_code();

    struct sigaction sa;
    memset(&sa, 0, sizeof(struct sigaction));
    sa.sa_handler = handle_sigint;
    TRY(Core::System::sigaction(SIGINT, &sa, nullptr));

    size_t depth = 0;
    bool new_function = true;

    g_debug_session->run(Debug::DebugSession::DesiredInitialDebugeeState::Running, [&](Debug::DebugSession::DebugBreakReason reason, Optional<PtraceRegisters> regs) {
        if (reason == Debug::DebugSession::DebugBreakReason::Exited) {
            outln("Program exited.");
            return Debug::DebugSession::DebugDecision::Detach;
        }

        if (reason == Debug::DebugSession::DebugBreakReason::Syscall) {
            print_syscall(regs.value(), depth + 1);
            return Debug::DebugSession::DebugDecision::ContinueBreakAtSyscall;
        }

#if ARCH(I386)
        const FlatPtr ip = regs.value().eip;
#else
        const FlatPtr ip = regs.value().rip;
#endif

        if (new_function) {
            auto function_name = g_debug_session->symbolicate(ip);
            print_function_call(function_name.value().symbol, depth);
            new_function = false;
            return Debug::DebugSession::ContinueBreakAtSyscall;
        }
        auto instruction = instrumented->get((void*)ip).value();

        if (instruction.mnemonic() == "RET") {
            if (depth != 0)
                --depth;
            return Debug::DebugSession::ContinueBreakAtSyscall;
        }

        // FIXME: we could miss some leaf functions that were called with a jump
        VERIFY(instruction.mnemonic() == "CALL");

        ++depth;
        new_function = true;

        return Debug::DebugSession::DebugDecision::SingleStep;
    });

    return 0;
}