-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebugger.cpp
More file actions
583 lines (543 loc) · 16.6 KB
/
debugger.cpp
File metadata and controls
583 lines (543 loc) · 16.6 KB
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
#include "debugger.h"
namespace {
struct reg_descriptor
{
std::string name;
size_t offset;
};
const std::vector<reg_descriptor> g_registers = {
{"rax", offsetof(user_regs_struct, rax)}, {"rbx", offsetof(user_regs_struct, rbx)},
{"rcx", offsetof(user_regs_struct, rcx)}, {"rdx", offsetof(user_regs_struct, rdx)},
{"rdi", offsetof(user_regs_struct, rdi)}, {"rsi", offsetof(user_regs_struct, rsi)},
{"rbp", offsetof(user_regs_struct, rbp)}, {"rsp", offsetof(user_regs_struct, rsp)},
{"r8", offsetof(user_regs_struct, r8)}, {"r9", offsetof(user_regs_struct, r9)},
{"r10", offsetof(user_regs_struct, r10)}, {"r11", offsetof(user_regs_struct, r11)},
{"r12", offsetof(user_regs_struct, r12)}, {"r13", offsetof(user_regs_struct, r13)},
{"r14", offsetof(user_regs_struct, r14)}, {"r15", offsetof(user_regs_struct, r15)},
{"rip", offsetof(user_regs_struct, rip)}, {"eflags", offsetof(user_regs_struct, eflags)}};
} // namespace
Debugger::Debugger()
: state(NOT_LOADED)
, pid(-1)
, entry_point(0)
{
if (cs_open(CS_ARCH_X86, CS_MODE_64, &capstone_handle) != CS_ERR_OK) {
std::cerr << "** fatal: failed to initialize capstone.\n";
exit(1);
}
cs_option(capstone_handle, CS_OPT_DETAIL, CS_OPT_ON);
}
Debugger::~Debugger() { cs_close(&capstone_handle); }
bool Debugger::parse_elf(const std::string &path)
{
int fd = open(path.c_str(), O_RDONLY);
if (fd < 0)
return false;
Elf64_Ehdr ehdr;
if (read(fd, &ehdr, sizeof(ehdr)) != sizeof(ehdr)) {
close(fd);
return false;
}
entry_point = ehdr.e_entry;
lseek(fd, ehdr.e_phoff, SEEK_SET);
for (int i = 0; i < ehdr.e_phnum; i++) {
Elf64_Phdr phdr;
read(fd, &phdr, sizeof(phdr));
if (phdr.p_type == PT_LOAD && (phdr.p_flags & PF_X)) {
text_segment.start = phdr.p_vaddr;
text_segment.end = phdr.p_vaddr + phdr.p_memsz;
break;
}
}
close(fd);
return true;
}
void Debugger::load_program(const std::string &path)
{
if (state != NOT_LOADED) {
std::cerr << "** program already loaded.\n";
return;
}
auto s = std::filesystem::status(path);
auto p = s.permissions();
bool is_exec = (p & (std::filesystem::perms::owner_exec | std::filesystem::perms::group_exec |
std::filesystem::perms::others_exec)) != std::filesystem::perms::none;
if (!std::filesystem::exists(s) || !std::filesystem::is_regular_file(s) || !is_exec) {
std::cerr << "** error: '" << path << "' is invalid or not executable.\n";
return;
}
program_path = path;
if (!parse_elf(path)) {
std::cerr << "** failed to load program.\n";
return;
}
std::cout << "** program '" << path << "' loaded. entry point 0x" << std::hex << entry_point << "\n";
state = LOADED;
}
void Debugger::load_initial_program(const std::string &path)
{
program_path = path;
if (!parse_elf(path)) {
std::cerr << "** failed to load program.\n";
exit(1);
}
std::cout << "** program '" << path << "' loaded. entry point 0x" << std::hex << entry_point << "\n";
state = LOADED;
}
void Debugger::start_program()
{
if (state == NOT_LOADED) {
std::cerr << "** no program loaded.\n";
return;
}
if (state == RUNNING) {
std::cerr << "** program already running.\n";
return;
}
pid = fork();
if (pid == 0) {
ptrace(PTRACE_TRACEME, 0, nullptr, nullptr);
execl(program_path.c_str(), program_path.c_str(), nullptr);
perror("execl");
exit(1);
} else if (pid > 0) {
int status;
waitpid(pid, &status, 0);
state = RUNNING;
std::cout << "** pid " << pid << "\n";
apply_all_breakpoints();
} else {
perror("fork");
}
}
void Debugger::run_program()
{
if (state == NOT_LOADED) {
std::cerr << "** no program loaded.\n";
return;
}
if (state == RUNNING) {
std::cout << "** program " << program_path << " is already running\n";
continue_execution();
return;
}
start_program();
if (state == RUNNING) {
continue_execution();
}
}
void Debugger::wait_for_signal()
{
int status;
waitpid(pid, &status, 0);
if (WIFEXITED(status)) {
std::cout << "** child process " << pid << " terminiated normally (code " << WEXITSTATUS(status) << ")\n";
state = LOADED;
pid = -1;
} else if (WIFSTOPPED(status)) {
int sig = WSTOPSIG(status);
if (sig == SIGTRAP) {
handle_breakpoint();
} else {
std::cout << "** child process " << pid << " stopped by signal " << sig << " (" << strsignal(sig) << ")\n";
}
} else if (WIFSIGNALED(status)) {
std::cout << "** child process " << pid << " killed by signal " << WTERMSIG(status) << "\n";
state = LOADED;
}
}
void Debugger::handle_breakpoint()
{
struct user_regs_struct regs;
ptrace(PTRACE_GETREGS, pid, nullptr, ®s);
uintptr_t pc = regs.rip - 1;
auto it = addr_to_bp.find(pc);
if (it != addr_to_bp.end()) {
regs.rip = pc;
ptrace(PTRACE_SETREGS, pid, nullptr, ®s);
print_instruction_at(pc);
}
}
void Debugger::apply_all_breakpoints()
{
for (auto &[id, bp] : breakpoints) {
uint64_t code = ptrace(PTRACE_PEEKTEXT, pid, (void *)bp.addr, nullptr);
ptrace(PTRACE_POKETEXT, pid, (void *)bp.addr, (code & ~0xFFULL) | 0xCC);
}
}
void Debugger::continue_execution()
{
if (state != RUNNING) {
std::cerr << "** program not running.\n";
return;
}
struct user_regs_struct regs;
ptrace(PTRACE_GETREGS, pid, nullptr, ®s);
uintptr_t pc = regs.rip;
auto it = addr_to_bp.find(pc);
if (it != addr_to_bp.end()) {
auto &bp = it->second;
uint64_t code = ptrace(PTRACE_PEEKTEXT, pid, (void *)pc, nullptr);
ptrace(PTRACE_POKETEXT, pid, (void *)pc, (code & ~0xFFULL) | (bp.original_data & 0xFF));
ptrace(PTRACE_SINGLESTEP, pid, nullptr, nullptr);
int status;
waitpid(pid, &status, 0);
ptrace(PTRACE_POKETEXT, pid, (void *)pc, (code & ~0xFFULL) | 0xCC);
}
ptrace(PTRACE_CONT, pid, nullptr, nullptr);
wait_for_signal();
}
void Debugger::set_breakpoint(uintptr_t addr)
{
if (state != RUNNING) {
std::cerr << "** program not running.\n";
return;
}
if (addr_to_bp.find(addr) != addr_to_bp.end()) {
std::cout << "** breakpoint already exists at 0x" << std::hex << addr << "\n";
return;
}
uint64_t original_data = ptrace(PTRACE_PEEKTEXT, pid, (void *)addr, nullptr);
uint64_t trap_data = (original_data & ~0xFFULL) | 0xCC;
ptrace(PTRACE_POKETEXT, pid, (void *)addr, trap_data);
addr_to_bp[addr] = {addr, original_data};
breakpoints[breakpoint_id_counter] = {addr, original_data};
breakpoint_id_counter++;
}
void Debugger::delete_breakpoint(int id)
{
if (state != RUNNING) {
std::cerr << "** program not running.\n";
return;
}
auto it = breakpoints.find(id);
if (it == breakpoints.end()) {
std::cerr << "** breakpoint " << id << " not found.\n";
return;
}
uintptr_t addr = it->second.addr;
uint64_t original_byte = it->second.original_data & 0xFF;
uint64_t current_code = ptrace(PTRACE_PEEKTEXT, pid, (void *)addr, nullptr);
if ((current_code & 0xFF) == 0xCC) {
uint64_t restored_code = (current_code & ~0xFFULL) | original_byte;
ptrace(PTRACE_POKETEXT, pid, (void *)addr, (void *)restored_code);
}
addr_to_bp.erase(addr);
breakpoints.erase(it);
std::cout << "** breakpoint " << id << " deleted at 0x" << std::hex << addr << "\n";
}
void Debugger::list_breakpoints()
{
for (const auto &[id, bp] : breakpoints) {
std::cout << " " << std::dec << id << ": " << std::hex << bp.addr << "\n";
}
}
void Debugger::print_instruction_at(uintptr_t pc)
{
cs_insn *insn;
uint8_t code_buf[15];
for (int i = 0; i < 15; i += 8) {
uint64_t word = ptrace(PTRACE_PEEKTEXT, pid, (void *)(pc + i), nullptr);
int copy_len = (15 - i > 8) ? 8 : 15 - i;
memcpy(code_buf + i, &word, copy_len);
}
for (int i = 0; i < 15; i++) {
auto it = addr_to_bp.find(pc + i);
if (it != addr_to_bp.end())
code_buf[i] = it->second.original_data & 0xFF;
}
size_t count = cs_disasm(capstone_handle, code_buf, 15, pc, 1, &insn);
if (count > 0) {
std::cout << "** breakpoint @ " << std::hex << std::setw(11) << std::right << pc << ": ";
std::stringstream ss;
for (int i = 0; i < insn[0].size; i++)
ss << std::hex << std::setw(2) << std::setfill('0') << (int)insn[0].bytes[i] << " ";
std::cout << std::left << std::setw(31) << std::setfill(' ') << ss.str();
std::cout << std::left << std::setw(10) << insn[0].mnemonic << insn[0].op_str << "\n";
cs_free(insn, count);
}
}
void Debugger::show_breakpoint_info(uintptr_t pc)
{
if (addr_to_bp.count(pc))
print_instruction_at(pc);
}
void Debugger::single_step()
{
if (state != RUNNING) {
std::cerr << "** program not running.\n";
return;
}
struct user_regs_struct regs;
ptrace(PTRACE_GETREGS, pid, nullptr, ®s);
uintptr_t pc = regs.rip;
auto it = addr_to_bp.find(pc);
if (it != addr_to_bp.end()) {
auto &bp = it->second;
uint64_t code = ptrace(PTRACE_PEEKTEXT, pid, (void *)pc, nullptr);
ptrace(PTRACE_POKETEXT, pid, (void *)pc, (code & ~0xFFULL) | (bp.original_data & 0xFF));
ptrace(PTRACE_SINGLESTEP, pid, nullptr, nullptr);
int status;
waitpid(pid, &status, 0);
ptrace(PTRACE_POKETEXT, pid, (void *)pc, (code & ~0xFFULL) | 0xCC);
} else {
ptrace(PTRACE_SINGLESTEP, pid, nullptr, nullptr);
int status;
waitpid(pid, &status, 0);
}
ptrace(PTRACE_GETREGS, pid, nullptr, ®s);
uintptr_t new_pc = regs.rip;
if (addr_to_bp.count(new_pc))
print_instruction_at(new_pc);
}
uint64_t Debugger::get_register_value(const std::string ®_name, struct user_regs_struct ®s)
{
for (const auto &rd : g_registers) {
if (rd.name == reg_name) {
return *(reinterpret_cast<uint64_t *>((uint8_t *)®s + rd.offset));
}
}
return 0;
}
void Debugger::get_register(const std::string ®)
{
if (state != RUNNING) {
std::cerr << "** program not running.\n";
return;
}
struct user_regs_struct regs;
ptrace(PTRACE_GETREGS, pid, nullptr, ®s);
uint64_t value = get_register_value(reg, regs);
std::cout << reg << " = " << std::dec << value << " (0x" << std::hex << value << ")\n";
}
void Debugger::set_register_value(const std::string ®_name, uint64_t value, struct user_regs_struct ®s)
{
for (const auto &rd : g_registers) {
if (rd.name == reg_name) {
*(reinterpret_cast<uint64_t *>((uint8_t *)®s + rd.offset)) = value;
return;
}
}
}
void print_reg(const std::string &name, unsigned long long val, bool force_fill = false)
{
std::cout << std::left << std::setw(4) << name << " ";
if (val == 0 && !force_fill)
std::cout << std::left << std::setw(18) << "0";
else {
if (force_fill)
std::cout << std::hex << std::setfill('0') << std::right << std::setw(16) << val << std::left << std::setfill(' ')
<< " ";
else
std::cout << std::hex << std::left << std::setw(18) << val;
}
}
void Debugger::get_registers()
{
if (state != RUNNING) {
std::cerr << "** program not running.\n";
return;
}
struct user_regs_struct regs;
ptrace(PTRACE_GETREGS, pid, nullptr, ®s);
print_reg("RAX", regs.rax);
print_reg("RBX", regs.rbx);
print_reg("RCX", regs.rcx);
print_reg("RDX", regs.rdx);
std::cout << "\n";
print_reg("R8", regs.r8);
print_reg("R9", regs.r9);
print_reg("R10", regs.r10);
print_reg("R11", regs.r11);
std::cout << "\n";
print_reg("R12", regs.r12);
print_reg("R13", regs.r13);
print_reg("R14", regs.r14);
print_reg("R15", regs.r15);
std::cout << "\n";
print_reg("RDI", regs.rdi);
print_reg("RSI", regs.rsi);
print_reg("RBP", regs.rbp);
print_reg("RSP", regs.rsp);
std::cout << "\n";
print_reg("RIP", regs.rip);
print_reg("FLAGS", regs.eflags, true);
std::cout << "\n";
std::cout << std::dec << std::setfill(' ');
}
void Debugger::set_register(const std::string ®, uint64_t value)
{
if (state != RUNNING) {
std::cerr << "** program not running.\n";
return;
}
struct user_regs_struct regs;
ptrace(PTRACE_GETREGS, pid, nullptr, ®s);
set_register_value(reg, value, regs);
ptrace(PTRACE_SETREGS, pid, nullptr, ®s);
}
void Debugger::dump_memory(uintptr_t addr)
{
if (state != RUNNING) {
std::cerr << "** program not running.\n";
return;
}
if (addr == 0) {
std::cout << "** no addr is given.\n";
return;
}
for (int line = 0; line < 5; line++) {
std::cout << " " << std::hex << std::setw(7) << std::setfill('0') << (addr + line * 16) << ": ";
uint8_t bytes[16];
for (int i = 0; i < 16; i++) {
bytes[i] = ptrace(PTRACE_PEEKTEXT, pid, (void *)(addr + line * 16 + i), nullptr) & 0xFF;
std::cout << std::setw(2) << std::setfill('0') << std::hex << (int)bytes[i] << " ";
}
std::cout << "|";
for (int i = 0; i < 16; i++)
std::cout << (char)((bytes[i] >= 32 && bytes[i] <= 126) ? bytes[i] : '.');
std::cout << "|\n";
}
}
void Debugger::disassemble(uintptr_t addr)
{
if (state != RUNNING) {
std::cerr << "** program not running.\n";
return;
}
if (addr == 0) {
std::cout << "** no addr is given.\n";
return;
}
cs_insn *insn;
uint8_t code[150];
for (int i = 0; i < 150; i++) {
uintptr_t current_ptr = addr + i;
code[i] = ptrace(PTRACE_PEEKTEXT, pid, (void *)(current_ptr), nullptr) & 0xFF;
auto it = addr_to_bp.find(current_ptr);
if (it != addr_to_bp.end())
code[i] = it->second.original_data & 0xFF;
}
size_t count = cs_disasm(capstone_handle, code, 150, addr, 10, &insn);
for (size_t i = 0; i < count; i++) {
if (insn[i].address >= text_segment.end) {
std::cout << "** the address is out of range\n";
break;
}
std::cout << " " << std::hex << std::setw(6) << std::setfill(' ') << std::right << insn[i].address << ": ";
std::string bytes_str = "";
char buf[4];
for (int j = 0; j < insn[i].size; j++) {
sprintf(buf, "%02x ", (int)insn[i].bytes[j]);
bytes_str += buf;
}
std::cout << std::setw(32) << std::setfill(' ') << std::left << bytes_str << std::setw(10) << insn[i].mnemonic
<< insn[i].op_str << "\n";
}
cs_free(insn, count);
}
void Debugger::show_vmmap()
{
if (state != RUNNING) {
std::cerr << "** program not running.\n";
return;
}
std::stringstream path;
path << "/proc/" << pid << "/maps";
std::ifstream maps(path.str());
std::string line;
while (getline(maps, line)) {
std::stringstream iss(line);
std::string addr_range, perms, offset;
iss >> addr_range >> perms >> offset;
size_t dash = addr_range.find('-');
std::cout << std::setfill('0') << std::setw(16) << std::right << addr_range.substr(0, dash) << "-" << std::setw(16)
<< addr_range.substr(dash + 1) << " " << perms.substr(0, 3) << " " << std::hex
<< stoull(offset, nullptr, 16) << "\n";
}
}
void Debugger::print_help()
{
std::cout << "Available commands:\nbreak {addr}, cont, delete {id}, disasm, dump, exit, get, getregs, help, list, "
"load, run, vmmap, set, si, start\n";
}
void Debugger::exit_debugger()
{
if (pid > 0) {
kill(pid, SIGKILL);
waitpid(pid, nullptr, 0);
}
exit(0);
}
void Debugger::handle_command(const std::string &line)
{
if (line.empty())
return;
std::stringstream iss(line);
std::string cmd;
iss >> cmd;
if (cmd == "load") {
std::string path;
iss >> path;
load_program(path);
} else if (cmd == "start")
start_program();
else if (cmd == "run" || cmd == "r")
run_program();
else if (cmd == "cont" || cmd == "c")
continue_execution();
else if (cmd == "break" || cmd == "b") {
std::string a;
iss >> a;
set_breakpoint(stoull(a, 0, 16));
} else if (cmd == "delete") {
int id;
iss >> id;
delete_breakpoint(id);
} else if (cmd == "list" || cmd == "l")
list_breakpoints();
else if (cmd == "si")
single_step();
else if (cmd == "get" || cmd == "g") {
std::string r;
iss >> r;
get_register(r);
} else if (cmd == "getregs")
get_registers();
else if (cmd == "set" || cmd == "s") {
std::string r;
uint64_t v;
iss >> r >> std::hex >> v;
set_register(r, v);
} else if (cmd == "dump" || cmd == "x") {
std::string a;
if (iss >> a)
dump_memory(stoull(a, 0, 16));
else
dump_memory(0);
} else if (cmd == "disasm" || cmd == "d") {
std::string a;
if (iss >> a)
disassemble(stoull(a, 0, 16));
else
disassemble(0);
} else if (cmd == "vmmap" || cmd == "m")
show_vmmap();
else if (cmd == "help" || cmd == "h")
print_help();
else if (cmd == "exit" || cmd == "q")
exit_debugger();
}
void Debugger::run(bool use_script, const std::string &script_file)
{
if (use_script) {
std::ifstream script(script_file);
std::string line;
while (getline(script, line))
handle_command(line);
} else {
std::string line;
while (std::cout << "sdb> " && getline(std::cin, line))
handle_command(line);
}
}