The Pedigree Project 0.1
Debugger.cc
1/*
2 * Copyright (c) 2008-2014, Pedigree Developers
3 *
4 * Please see the CONTRIB file in the root of the source tree for a full
5 * list of contributors.
6 *
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
10 *
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 */
19
20#include "pedigree/kernel/Log.h"
21#include "pedigree/kernel/Service.h"
22#include "pedigree/kernel/ServiceFeatures.h"
23#include "pedigree/kernel/ServiceManager.h"
24#include "pedigree/kernel/debugger/Debugger.h"
25#include "pedigree/kernel/debugger/DebuggerCommand.h"
26#include "pedigree/kernel/debugger/DebuggerIO.h"
27#include "pedigree/kernel/debugger/LocalIO.h"
28#include "pedigree/kernel/debugger/SerialIO.h"
29#include "pedigree/kernel/debugger/commands/AllocationCommand.h"
30#include "pedigree/kernel/debugger/commands/Backtracer.h"
31#include "pedigree/kernel/debugger/commands/BreakpointCommand.h"
32#include "pedigree/kernel/debugger/commands/CpuInfoCommand.h"
33#include "pedigree/kernel/debugger/commands/DevicesCommand.h"
34#include "pedigree/kernel/debugger/commands/DisassembleCommand.h"
35#include "pedigree/kernel/debugger/commands/DumpCommand.h"
36#include "pedigree/kernel/debugger/commands/HelpCommand.h"
37#include "pedigree/kernel/debugger/commands/IoCommand.h"
38#include "pedigree/kernel/debugger/commands/IrqsCommand.h"
39#include "pedigree/kernel/debugger/commands/LocksCommand.h"
40#include "pedigree/kernel/debugger/commands/LogViewer.h"
41#include "pedigree/kernel/debugger/commands/LookupCommand.h"
42#include "pedigree/kernel/debugger/commands/MappingCommand.h"
43#include "pedigree/kernel/debugger/commands/MemoryInspector.h"
44#include "pedigree/kernel/debugger/commands/ModulesCommand.h"
45#include "pedigree/kernel/debugger/commands/PanicCommand.h"
46#include "pedigree/kernel/debugger/commands/QuitCommand.h"
47#include "pedigree/kernel/debugger/commands/SlamCommand.h"
48#include "pedigree/kernel/debugger/commands/StepCommand.h"
49#include "pedigree/kernel/debugger/commands/SyscallTracerCommand.h"
50#include "pedigree/kernel/debugger/commands/ThreadsCommand.h"
51#include "pedigree/kernel/debugger/commands/TraceCommand.h"
52#include "pedigree/kernel/graphics/GraphicsService.h"
53#include "pedigree/kernel/machine/Display.h"
54#include "pedigree/kernel/machine/Keyboard.h"
55#include "pedigree/kernel/machine/Machine.h"
56#include "pedigree/kernel/machine/Serial.h"
57#include "pedigree/kernel/processor/InterruptManager.h"
58#include "pedigree/kernel/processor/Processor.h"
59#include "pedigree/kernel/processor/ProcessorInformation.h"
60#include "pedigree/kernel/processor/VirtualAddressSpace.h"
61#include "pedigree/kernel/processor/state.h"
62#include "pedigree/kernel/utilities/String.h"
63#include "pedigree/kernel/utilities/utility.h"
64
65class Thread;
66
68
72static int getCommandMatchingPrefix(char* prefix, DebuggerCommand** pCommands, size_t nCmds,
73 size_t start) {
74 for (size_t i = start; i < nCmds; i++) {
75 if (!StringCompareN(pCommands[i]->getString(), prefix, StringLength(prefix)))
76 return i;
77 }
78 return -1;
79}
80
84static bool matchesCommand(char* pStr, DebuggerCommand* pCommand) {
85 const size_t commandLength = StringLength(pCommand->getString());
86 if (StringCompareN(pCommand->getString(), pStr, commandLength)) {
87 return false;
88 }
89
90 const size_t inputLength = StringLength(pStr);
91 if (inputLength > commandLength && pStr[commandLength] != ' ' && pStr[commandLength] != '\t') {
92 return false;
93 }
94 if (inputLength == commandLength) {
95 // Existing commands use the command name to select no-argument
96 // behaviour, so preserve it while rejecting run-together prefixes.
97 return true;
98 }
99
100 MemoryCopy(pStr, pStr + commandLength + 1, inputLength - commandLength);
101 return true;
102}
103
104Debugger::Debugger() : m_pTempState(0), m_nIoType(DEBUGGER) {}
105
106Debugger::~Debugger() {}
107
109 if (!InterruptManager::instance().registerInterruptHandlerDebugger(
110 InterruptManager::instance().getBreakpointInterruptNumber(), this))
111 ERROR_NOLOCK("Debugger: breakpoint interrupt registration failed!");
112 if (!InterruptManager::instance().registerInterruptHandlerDebugger(
113 InterruptManager::instance().getDebugInterruptNumber(), this))
114 ERROR_NOLOCK("Debugger: debug interrupt registration failed!");
115}
116
118void Debugger::start(InterruptState& state, LargeStaticString& description) {
119 // Quiescing another CPU can fail while it holds an IRQ-disabling lock.
120 // Preserve the initiating exception before entering that barrier.
121 if (Machine::instance().getNumSerial()) {
122 Serial* serial = Machine::instance().getSerial(0);
123 if (serial) {
124 LargeStaticString entry("\nDebugger entry RIP=");
125 entry.append(state.getInstructionPointer(), 16);
126 entry += " CPU=";
127 entry.append(Processor::index(), 10);
128 entry += ": ";
129 entry += description;
130 entry += "\n";
131 serial->write_str(entry);
132 }
133 }
134#if MULTIPROCESSOR
135 const bool processorsQuiesced = Machine::instance().quiesceAllOtherProcessors();
136 if (!processorsQuiesced) {
137 ERROR_NOLOCK("Debugger: not all other processors quiesced");
138 }
139#endif
140
141 Log::LogEntry entry;
142 entry << Log::Notice << " << Flushing log content >>";
143 Log::instance().addEntry(entry);
144#if defined(VALGRIND) || defined(HAS_SANITIZERS)
146#endif
147 static String graphicsService("graphics");
148
149 // Drop out of whatever graphics mode we were in
151 ByteSet(&params, 0, sizeof(params));
152 params.wantTextMode = false;
153
154 ServiceFeatures* pFeatures = nullptr;
155 Service* pService = nullptr;
156 bool bSuccess = false;
157 if (ServiceManager::instance().tryGetService(graphicsService, pService, pFeatures) &&
158 pFeatures->provides(ServiceFeatures::probe)) {
159 bSuccess =
160 pService->serve(ServiceFeatures::probe, reinterpret_cast<void*>(&params), sizeof(params));
161 }
162
163 if (bSuccess && params.providerFound) {
164 // try and get back to text mode
165 if (params.providerResult.pDisplay) {
166 params.providerResult.pDisplay->setScreenMode(0);
167 }
168 }
169
170// We take a copy of the interrupt state here so that we can replace it with
171// another thread's interrupt state should we decide to switch threads. The
172// current thread, in case we decide to switch.
173#if THREADS
174 Thread* pThread = Processor::information().getCurrentThread();
175#endif
176
177 bool debugState = Machine::instance().getKeyboard()->getDebugState();
178 Machine::instance().getKeyboard()->setDebugState(true);
179
180 DebuggerIO* pInterfaces[2] = {0};
181
182#if !DONT_LOG_TO_SERIAL
183 static SerialIO serialIO(Machine::instance().getSerial(0));
184 serialIO.initialise();
185#endif
186
187 /*
188 * I/O implementations.
189 */
190 int nInterfaces = 0;
191 if (Machine::instance().getNumVga()) // Not all machines have "VGA", so handle that
192 {
193 static LocalIO localIO(Machine::instance().getVga(0), Machine::instance().getKeyboard());
194#if DONT_LOG_TO_SERIAL
195 pInterfaces[0] = &localIO;
196 nInterfaces = 1;
197#else
198 pInterfaces[0] = &localIO;
199 pInterfaces[1] = &serialIO;
200 nInterfaces = 2;
201#endif
202 }
203#if !DONT_LOG_TO_SERIAL
204 else {
205 pInterfaces[0] = &serialIO;
206 nInterfaces = 1;
207 }
208#endif
209
210 if (!nInterfaces) {
211 // Oops, system doesn't support any output mechanisms!
212 ERROR_NOLOCK(
213 "This machine/CPU combination doesn't support any output "
214 "methods for the debugger!");
215 }
216
217 // IO interface.
218 DebuggerIO* pIo = 0;
219 int nChosenInterface = -1;
220
221 // Commands.
222 static DisassembleCommand disassembler;
223 static LogViewer logViewer;
224 static Backtracer backtracer;
225 static QuitCommand quit;
226 static BreakpointCommand breakpoint;
227 static DumpCommand dump;
228 static StepCommand step;
229 static MemoryInspector memory;
230 static PanicCommand panic;
231 static CpuInfoCommand cpuInfo;
232 static IoCommand io;
233 static IrqsCommand irqs;
234 static DevicesCommand devices;
235 static SyscallTracerCommand syscallTracer;
236 static LookupCommand lookup;
237 static HelpCommand help;
238 static MappingCommand mapping;
239 static ModulesCommand modules;
240 static TraceCommand trace;
241
242#if THREADS
243 static ThreadsCommand threads;
244
245 threads.setPointers(&pThread, &state);
246#endif
247
248 DebuggerCommand* pCommands[] = {
249 &syscallTracer,
250 &disassembler,
251 &logViewer,
252 &backtracer,
253 &quit,
254 &breakpoint,
255 &dump,
256 &step,
257 &memory,
258 &trace,
259 &panic,
260 &cpuInfo,
261 &devices,
262#if THREADS
263 &threads,
264#endif
265 &io,
266 &irqs,
267 &g_AllocationCommand,
268 &g_SlamCommand,
269 &lookup,
270 &help,
271 &g_LocksCommand,
272 &mapping,
273 &modules,
274 };
275 const size_t nCommands = sizeof(pCommands) / sizeof(pCommands[0]);
276
277 // Are we going to jump directly into the tracer? In which case bypass
278 // device detection.
279 int n = trace.execTrace();
280 if (n == -1) {
281 // Write a "Press any key..." message to each device, then poll each
282 // device. The first one with data waiting becomes the active device,
283 // all others are locked out.
284 for (int i = 0; i < nInterfaces; i++) {
285 pInterfaces[i]->disableCli();
286 pInterfaces[i]->drawString("Press any key to enter the debugger...", 0, 0,
287 DebuggerIO::LightBlue, DebuggerIO::Black);
289 str += description;
290 pInterfaces[i]->drawString(str, 2, 0, DebuggerIO::LightBlue, DebuggerIO::Black);
291 }
292 // Poll each device.
293 while (pIo == 0) {
294 for (int i = 0; i < nInterfaces; i++) {
295 char c = pInterfaces[i]->getCharNonBlock();
296 if ((c >= 32 && static_cast<unsigned char>(c) <= 127) || c == '\n' || c == 0x08 ||
297 c == '\r' || c == 0x09) {
298 pIo = pInterfaces[i];
299 nChosenInterface = i;
300 break;
301 }
302 }
303 if (!pIo)
305 }
306 } else {
307 pIo = pInterfaces[n];
308 nChosenInterface = n;
309 }
310 pIo->readDimensions();
311
312 // Say sorry to the losers...
313 for (int i = 0; i < nInterfaces; i++)
314 if (pIo != pInterfaces[i])
315 pInterfaces[i]->drawString("Locked by another device.", 1, 0, DebuggerIO::LightRed,
316 DebuggerIO::Black);
317
318 pIo->setCliUpperLimit(1); // Give us room for a status bar on top.
319 pIo->setCliLowerLimit(1); // And a status bar on the bottom.
320 pIo->enableCli(); // Start CLI mode.
321
322 description += "\n";
323 pIo->writeCli(description, DebuggerIO::Yellow, DebuggerIO::Black);
324
325 description.clear();
326 description += "Kernel heap ends at ";
327 description.append(
328 reinterpret_cast<uintptr_t>(VirtualAddressSpace::getKernelAddressSpace().m_HeapEnd), 16);
329 description += "\n";
330 pIo->writeCli(description, DebuggerIO::Yellow, DebuggerIO::Black);
331
332 // Main CLI loop.
333 bool bKeepGoing = false;
334 do {
335 HugeStaticString command;
336 HugeStaticString output;
337 // Should we jump directly in to the tracer?
338 if (trace.execTrace() != -1) {
339 bKeepGoing = trace.execute(command, output, state, pIo);
340 continue;
341 } else
342 trace.setInterface(nChosenInterface);
343 // Clear the top and bottom status lines.
344 pIo->drawHorizontalLine(' ', 0, 0, pIo->getWidth() - 1, DebuggerIO::White, DebuggerIO::Green);
345 pIo->drawHorizontalLine(' ', pIo->getHeight() - 1, 0, pIo->getWidth() - 1, DebuggerIO::White,
346 DebuggerIO::Green);
347 // Write the correct text in the upper status line.
348 pIo->drawString("Pedigree debugger", 0, 0, DebuggerIO::White, DebuggerIO::Green);
349
350 bool matchedCommand = false;
351 DebuggerCommand* pAutoComplete = 0;
352 while (1) {
353 // Try and get a character from the CLI, passing in a buffer to
354 // populate and an autocomplete command for if the user presses TAB
355 // (if one is defined).
356 if (pIo->readCli(command, pAutoComplete))
357 break; // Command complete, try and parse it.
358
359 // The command wasn't complete - let's parse it and try and get an
360 // autocomplete string.
363 matchedCommand = false;
364 for (size_t i = 0; i < nCommands; i++) {
365 // TODO: This cast is completly wrong. As I said, don't touch
366 // (as in 'write') StaticString's
367 // internal string. The const is not there because I don't
368 // like you :-), it is there because directly writing is
369 // not garantueed to work (and it actually will break our
370 // code).
371 if (matchesCommand(const_cast<char*>(static_cast<const char*>(command)), pCommands[i])) {
372 str2 = static_cast<const char*>(pCommands[i]->getString());
373 str2 += ' ';
374 pCommands[i]->autocomplete(command, str);
375 matchedCommand = true;
376 break;
377 }
378 }
379
380 pAutoComplete = 0;
381 if (!matchedCommand) {
382 int i = -1;
383 while ((i = getCommandMatchingPrefix(const_cast<char*>(static_cast<const char*>(command)),
384 pCommands, nCommands, i + 1)) != -1) {
385 if (!pAutoComplete)
386 pAutoComplete = pCommands[i];
387 str += static_cast<const char*>(pCommands[i]->getString());
388 str += " ";
389 }
390 }
391
392 pIo->drawHorizontalLine(' ', pIo->getHeight() - 1, 0, pIo->getWidth() - 1, DebuggerIO::White,
393 DebuggerIO::Green);
394 pIo->drawString(str2, pIo->getHeight() - 1, 0, DebuggerIO::Yellow, DebuggerIO::Green);
395 pIo->drawString(str, pIo->getHeight() - 1, str2.length(), DebuggerIO::White,
396 DebuggerIO::Green);
397 }
398
399 // A command was entered.
400 bool bValidCommand = false;
401 for (size_t i = 0; i < nCommands; i++) {
402 if (matchesCommand(const_cast<char*>(static_cast<const char*>(command)), pCommands[i])) {
403 bKeepGoing = pCommands[i]->execute(command, output, state, pIo);
404 pIo->writeCli(output, DebuggerIO::LightGrey, DebuggerIO::Black);
405 bValidCommand = true;
406 }
407 }
408
409 if (!bValidCommand) {
410 pIo->writeCli("Unrecognised command.\n", DebuggerIO::LightGrey, DebuggerIO::Black);
411 bKeepGoing = true;
412 }
413
414 } while (bKeepGoing);
415 if (Machine::instance().getNumVga())
416 pInterfaces[0]->destroy(); // Causes rememberMode to be called twice.
417#if !DONT_LOG_TO_SERIAL
418 serialIO.destroy();
419#endif
420
421 Machine::instance().getKeyboard()->setDebugState(debugState);
422#if MULTIPROCESSOR
423 if (processorsQuiesced && !Machine::instance().resumeAllOtherProcessors()) {
424 ERROR_NOLOCK("Debugger: not all quiesced processors resumed");
425 }
426#endif
427}
428
429void Debugger::interrupt(size_t interruptNumber, InterruptState& state) {
430 LargeStaticString description;
431 // We switch here on the interrupt number, and dispatch accordingly.
432 if (interruptNumber == InterruptManager::instance().getBreakpointInterruptNumber()) {
433 // Here we check to see if the breakpoint was caused by an assertion, or
434 // a fatal error.
435 if (state.getRegister(0) == ASSERT_FAILED_SENTINEL) {
436 // As it's an assert or fatal, we assume state.getRegister(1) is a
437 // pointer to a descriptive string.
438 const char* pDescription = reinterpret_cast<const char*>(state.getRegister(1));
439 description += pDescription;
440 } else {
441 description += "Breakpoint exception.";
442 }
443 start(state, description);
444 } else if (interruptNumber == InterruptManager::instance().getDebugInterruptNumber()) {
445 Processor::setSingleStep(false, state);
446 description = "Debug/trap exception";
447 start(state, description);
448 }
449}
virtual const NormalStaticString getString()=0
virtual bool execute(const HugeStaticString &input, HugeStaticString &output, InterruptState &state, DebuggerIO *screen)=0
virtual void autocomplete(const HugeStaticString &input, HugeStaticString &output)=0
virtual void enableCli()=0
virtual bool readCli(HugeStaticString &str, DebuggerCommand *pAutoComplete)
Definition DebuggerIO.cc:25
virtual void setCliUpperLimit(size_t nlines)=0
virtual void drawString(const char *str, size_t row, size_t col, Colour foreColour, Colour backColour)=0
virtual size_t getWidth()=0
virtual void writeCli(const char *str, Colour foreColour, Colour backColour)
virtual void drawHorizontalLine(char c, size_t row, size_t colStart, size_t colEnd, Colour foreColour, Colour backColour)=0
void start(InterruptState &state, LargeStaticString &description)
Definition Debugger.cc:118
void initialise()
Definition Debugger.cc:108
virtual void interrupt(size_t interruptNumber, InterruptState &state)
Definition Debugger.cc:429
static Debugger m_Instance
Definition Debugger.h:86
virtual bool setScreenMode(ScreenMode sm)
Definition Display.cc:90
static EXPORTED_PUBLIC InterruptManager & instance()
virtual void setDebugState(bool enableDebugState)=0
EXPORTED_PUBLIC void addEntry(const LogEntry &entry, bool lock=true)
Definition Log.cc:612
static EXPORTED_PUBLIC Log & instance()
Definition Log.cc:117
virtual MUST_USE_RESULT bool quiesceAllOtherProcessors()
Definition Machine.cc:149
virtual Keyboard * getKeyboard()=0
virtual Serial * getSerial(size_t n)=0
virtual size_t getNumVga()=0
static void halt()
static ProcessorInformation & information()
static void pause()
static void setSingleStep(bool bEnable, InterruptState &state)
static size_t index()
virtual bool provides(Type service)
virtual bool serve(ServiceFeatures::Type type, void *pData, size_t dataLen)=0
SchedulerState & state()
Definition Thread.cc:832
bool start()
Definition Thread.cc:751
void setPointers(Thread **ppThread, InterruptState *pState)
static EXPORTED_PUBLIC VirtualAddressSpace & getKernelAddressSpace()
void EXPORTED_PUBLIC panic(const char *msg) NORETURN
Definition panic.cc:118