summaryrefslogtreecommitdiffhomepage
path: root/dev/LibDebugger/src/POSIXContract.cc
blob: 3caeabf7f3f0b8bb61a1f27ebb7e43304f9e8a8c (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
/***
	(C) 2025 Amlal El Mahrouss
 */

#include <LibCompiler/Defines.h>
#include <Vendor/Dialogs.h>
#include <LibDebugger/POSIXContract.h>
#include <cstdint>
#include <string>

#ifndef _WIN32

static bool										 kKeepRunning = false;
static LibDebugger::POSIX::POSIXDebuggerContract kDebugger;
static pid_t									 kPID = 0L;

/// @internal
/// @brief Handles CTRL-C signal on debugger.
static void dbgl_ctrlc_handler(std::int32_t _)
{
	if (!kPID)
	{
		return;
	}

	auto list = kDebugger.Get();

	LibDebugger::CAddress addr = (LibDebugger::CAddress)list[list.size() - 1];

	if (!addr)
	{
		pfd::notify("Debugger Event", "Invalid breakpoint at: " + std::to_string(list[list.size() - 1]));
		return;
	}

	kDebugger.Break(addr);

	pfd::notify("Debugger Event", "Breakpoint at: " + std::to_string(list[list.size() - 1]));

	kKeepRunning = false;
}

LIBCOMPILER_MODULE(DebuggerPOSIX)
{
	pfd::notify("Debugger Event", "NeKernel Debugger\n(C) 2025 Amlal El Mahrouss, all rights reserved.");

	if (argc >= 3 && std::string(argv[1]) == "-p" &&
		argv[2] != nullptr)
	{
		kPID = std::stoi(argv[2]);
		kDebugger.Attach(kPID);
	}

	::signal(SIGINT, dbgl_ctrlc_handler);

	while (YES)
	{
		if (kKeepRunning)
		{
			continue;
		}

		std::string cmd;
		std::getline(std::cin, cmd);

		if (cmd == "c" ||
			cmd == "cont")
		{
			kDebugger.Continue();
			kKeepRunning = true;

			std::cout << "[+] Continuing...\n";
			pfd::notify("Debugger Event", "Continuing...");
		}

		if (cmd == "d" ||
			cmd == "detach")
			kDebugger.Detach();

		if (cmd == "attach")
		{
			std::cout << "[?] Enter a PID to attach on: ";

			std::getline(std::cin, cmd);
			kPID = std::stoi(cmd.c_str());

			pfd::notify("Debugger Event", "Attach process: " + std::to_string(kPID));

			kDebugger.Attach(kPID);
		}

		if (cmd == "exit")
		{
			if (kPID > 0)
				kDebugger.Detach();

			break;
		}

		if (cmd == "break" ||
			cmd == "b")
		{
			std::cout << "[?] Enter an address/symbol to add a break on: ";

			std::getline(std::cin, cmd);

			auto addr = std::stoul(cmd.c_str(), nullptr, 16);

			try
			{
				pfd::notify("Debugger Event", "Add Breakpoint at: " + std::to_string(addr));
			}
			catch (...)
			{
				pfd::notify("Debugger Event", "Add Breakpoint at: " + cmd);
			}

			LibDebugger::CAddress breakpoint_addr = reinterpret_cast<LibDebugger::CAddress>(addr);

			if (breakpoint_addr)
				kDebugger.Break(breakpoint_addr);
		}
	}

	return EXIT_SUCCESS;
}

#endif