summaryrefslogtreecommitdiff
path: root/Applications/Debugger/main.cpp
blob: 94fbe0ffcbcd98be6e5a54fe0d7ee44e6391ec48 (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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
/*
 * Copyright (c) 2020, Itamar S. <itamar8910@gmail.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "DebugSession.h"
#include <AK/Assertions.h>
#include <AK/ByteBuffer.h>
#include <AK/LogStream.h>
#include <AK/StringBuilder.h>
#include <AK/kmalloc.h>
#include <LibC/sys/arch/i386/regs.h>
#include <LibCore/File.h>
#include <LibX86/Disassembler.h>
#include <LibX86/Instruction.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

static int usage()
{
    printf("usage: sdb [command...]\n");
    return 1;
}

OwnPtr<DebugSession> g_debug_session;

static void handle_sigint(int)
{
    printf("Debugger: SIGINT\n");

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

String get_command()
{
    printf("(sdb) ");
    fflush(stdout);
    char* line = nullptr;
    size_t allocated_size = 0;
    ssize_t nread = getline(&line, &allocated_size, stdin);
    if (nread < 0) {
        if (errno == 0) {
            fprintf(stderr, "\n");
        } else {
            perror("getline");
            exit(1);
        }
    }
    String command(line);
    free(line);
    if (command.ends_with('\n'))
        command = command.substring(0, command.length() - 1);
    return command;
}

void handle_print_registers(const PtraceRegisters& regs)
{
    printf("eax: 0x%x\n", regs.eax);
    printf("ecx: 0x%x\n", regs.ecx);
    printf("edx: 0x%x\n", regs.edx);
    printf("ebx: 0x%x\n", regs.ebx);
    printf("esp: 0x%x\n", regs.esp);
    printf("ebp: 0x%x\n", regs.ebp);
    printf("esi: 0x%x\n", regs.esi);
    printf("edi: 0x%x\n", regs.edi);
    printf("eip: 0x%x\n", regs.eip);
    printf("eflags: 0x%x\n", regs.eflags);
}

bool handle_disassemble_command(const String& command, void* first_instruction)
{
    auto parts = command.split(' ');
    size_t number_of_instructions_to_disassemble = 5;
    if (parts.size() == 2) {
        bool ok;
        number_of_instructions_to_disassemble = parts[1].to_uint(ok);
        if (!ok)
            return false;
    }

    // FIXME: Instead of using a fixed "dump_size",
    //        we can feed instructions to the disassembler one by one
    constexpr size_t dump_size = 0x100;
    ByteBuffer code;
    for (size_t i = 0; i < dump_size / sizeof(u32); ++i) {
        auto value = g_debug_session->peek(reinterpret_cast<u32*>(first_instruction) + i);
        if (!value.has_value())
            break;
        code.append(&value, sizeof(u32));
    }

    X86::SimpleInstructionStream stream(code.data(), code.size());
    X86::Disassembler disassembler(stream);

    for (size_t i = 0; i < number_of_instructions_to_disassemble; ++i) {
        auto offset = stream.offset();
        auto insn = disassembler.next();
        if (!insn.has_value())
            break;

        printf(String::format("   %08x ", offset + reinterpret_cast<size_t>(first_instruction)).characters());
        printf("<+%lu>:\t", reinterpret_cast<size_t>(offset));
        printf("%s\n", insn.value().to_string(offset).characters());
    }

    return true;
}

bool handle_breakpoint_command(const String& command)
{
    auto parts = command.split(' ');
    if (parts.size() != 2)
        return false;

    u32 breakpoint_address = strtoul(parts[1].characters(), nullptr, 16);
    if (errno != 0)
        return false;
    bool success = g_debug_session->insert_breakpoint(reinterpret_cast<void*>(breakpoint_address));
    if (!success) {
        fprintf(stderr, "coult not insert breakpoint at: 0x%x\n", breakpoint_address);
        return false;
    }
    return true;
}

void print_help()
{
    printf("Options:\n"
           "cont - Continue execution\n"
           "regs - Print registers\n"
           "dis <number of instructions> - Print disassembly\n"
           "bp <address> - Insert a breakpoint\n");
}

int main(int argc, char** argv)
{
    if (pledge("stdio proc exec rpath", nullptr) < 0) {
        perror("pledge");
        return 1;
    }

    if (argc == 1)
        return usage();

    StringBuilder command;
    command.append(argv[1]);
    for (int i = 2; i < argc; ++i) {
        command.appendf("%s ", argv[i]);
    }

    auto result = DebugSession::exec_and_attach(command.to_string());
    if (!result) {
        fprintf(stderr, "Failed to start debugging session for: \"%s\"\n", command.to_string().characters());
        exit(1);
    }
    g_debug_session = result.release_nonnull();

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

    bool rc = g_debug_session->insert_breakpoint(g_debug_session->get_entry_point().as_ptr());
    ASSERT(rc);

    g_debug_session->run([&](DebugSession::DebugBreakReason reason, Optional<PtraceRegisters> optional_regs) {
        if (reason == DebugSession::DebugBreakReason::Exited) {
            printf("Program exited.\n");
            return DebugSession::DebugDecision::Detach;
        }

        ASSERT(optional_regs.has_value());
        const PtraceRegisters& regs = optional_regs.value();

        printf("Program is stopped at: 0x%x\n", regs.eip);
        for (;;) {
            auto command = get_command();
            bool success = false;

            if (command == "cont") {
                return DebugSession::DebugDecision::Continue;
            }

            if (command == "regs") {
                handle_print_registers(regs);
                success = true;

            } else if (command.starts_with("dis")) {
                success = handle_disassemble_command(command, reinterpret_cast<void*>(regs.eip));

            } else if (command.starts_with("bp")) {
                success = handle_breakpoint_command(command);
            }

            if (!success)
                print_help();
        }
    });
}