all repos — mgba @ e7028e4b296bdfdb6e484b9a116cd8fe9f66a11d

mGBA Game Boy Advance Emulator

src/debugger/cli-debugger.c (view raw)

   1/* Copyright (c) 2013-2014 Jeffrey Pfau
   2 *
   3 * This Source Code Form is subject to the terms of the Mozilla Public
   4 * License, v. 2.0. If a copy of the MPL was not distributed with this
   5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
   6#include <mgba/internal/debugger/cli-debugger.h>
   7
   8#include <mgba/internal/debugger/symbols.h>
   9
  10#include <mgba/core/core.h>
  11#include <mgba/core/version.h>
  12#include <mgba/internal/debugger/parser.h>
  13#include <mgba-util/string.h>
  14#include <mgba-util/vfs.h>
  15
  16#ifdef ENABLE_SCRIPTING
  17#include <mgba/core/scripting.h>
  18#endif
  19
  20#if !defined(NDEBUG) && !defined(_WIN32)
  21#include <signal.h>
  22#endif
  23
  24#ifdef USE_PTHREADS
  25#include <pthread.h>
  26#endif
  27
  28const char* ERROR_MISSING_ARGS = "Arguments missing"; // TODO: share
  29const char* ERROR_OVERFLOW = "Arguments overflow";
  30const char* ERROR_INVALID_ARGS = "Invalid arguments";
  31const char* INFO_BREAKPOINT_ADDED = "Added breakpoint #%" PRIz "i\n";
  32const char* INFO_WATCHPOINT_ADDED = "Added watchpoint #%" PRIz "i\n";
  33
  34static struct ParseTree* _parseTree(const char** string);
  35static bool _doTrace(struct CLIDebugger* debugger);
  36
  37#if !defined(NDEBUG) && !defined(_WIN32)
  38static void _breakInto(struct CLIDebugger*, struct CLIDebugVector*);
  39#endif
  40static void _continue(struct CLIDebugger*, struct CLIDebugVector*);
  41static void _disassemble(struct CLIDebugger*, struct CLIDebugVector*);
  42static void _next(struct CLIDebugger*, struct CLIDebugVector*);
  43static void _print(struct CLIDebugger*, struct CLIDebugVector*);
  44static void _printBin(struct CLIDebugger*, struct CLIDebugVector*);
  45static void _printHex(struct CLIDebugger*, struct CLIDebugVector*);
  46static void _printStatus(struct CLIDebugger*, struct CLIDebugVector*);
  47static void _printHelp(struct CLIDebugger*, struct CLIDebugVector*);
  48static void _quit(struct CLIDebugger*, struct CLIDebugVector*);
  49static void _readByte(struct CLIDebugger*, struct CLIDebugVector*);
  50static void _reset(struct CLIDebugger*, struct CLIDebugVector*);
  51static void _readHalfword(struct CLIDebugger*, struct CLIDebugVector*);
  52static void _readWord(struct CLIDebugger*, struct CLIDebugVector*);
  53static void _setBreakpoint(struct CLIDebugger*, struct CLIDebugVector*);
  54static void _clearBreakpoint(struct CLIDebugger*, struct CLIDebugVector*);
  55static void _listBreakpoints(struct CLIDebugger*, struct CLIDebugVector*);
  56static void _setReadWriteWatchpoint(struct CLIDebugger*, struct CLIDebugVector*);
  57static void _setReadWatchpoint(struct CLIDebugger*, struct CLIDebugVector*);
  58static void _setWriteWatchpoint(struct CLIDebugger*, struct CLIDebugVector*);
  59static void _setWriteChangedWatchpoint(struct CLIDebugger*, struct CLIDebugVector*);
  60static void _listWatchpoints(struct CLIDebugger*, struct CLIDebugVector*);
  61static void _trace(struct CLIDebugger*, struct CLIDebugVector*);
  62static void _writeByte(struct CLIDebugger*, struct CLIDebugVector*);
  63static void _writeHalfword(struct CLIDebugger*, struct CLIDebugVector*);
  64static void _writeRegister(struct CLIDebugger*, struct CLIDebugVector*);
  65static void _writeWord(struct CLIDebugger*, struct CLIDebugVector*);
  66static void _dumpByte(struct CLIDebugger*, struct CLIDebugVector*);
  67static void _dumpHalfword(struct CLIDebugger*, struct CLIDebugVector*);
  68static void _dumpWord(struct CLIDebugger*, struct CLIDebugVector*);
  69#ifdef ENABLE_SCRIPTING
  70static void _source(struct CLIDebugger*, struct CLIDebugVector*);
  71#endif
  72static void _backtrace(struct CLIDebugger*, struct CLIDebugVector*);
  73static void _finish(struct CLIDebugger*, struct CLIDebugVector*);
  74static void _setStackTraceMode(struct CLIDebugger*, struct CLIDebugVector*);
  75static void _setSymbol(struct CLIDebugger*, struct CLIDebugVector*);
  76static void _findSymbol(struct CLIDebugger*, struct CLIDebugVector*);
  77
  78static struct CLIDebuggerCommandSummary _debuggerCommands[] = {
  79	{ "backtrace", _backtrace, "i", "Print backtrace of all or specified frames" },
  80	{ "break", _setBreakpoint, "Is", "Set a breakpoint" },
  81	{ "continue", _continue, "", "Continue execution" },
  82	{ "delete", _clearBreakpoint, "I", "Delete a breakpoint or watchpoint" },
  83	{ "disassemble", _disassemble, "Ii", "Disassemble instructions" },
  84	{ "finish", _finish, "", "Execute until current stack frame returns" },
  85	{ "help", _printHelp, "S", "Print help" },
  86	{ "listb", _listBreakpoints, "", "List breakpoints" },
  87	{ "listw", _listWatchpoints, "", "List watchpoints" },
  88	{ "next", _next, "", "Execute next instruction" },
  89	{ "print", _print, "S+", "Print a value" },
  90	{ "print/t", _printBin, "S+", "Print a value as binary" },
  91	{ "print/x", _printHex, "S+", "Print a value as hexadecimal" },
  92	{ "quit", _quit, "", "Quit the emulator" },
  93	{ "reset", _reset, "", "Reset the emulation" },
  94	{ "r/1", _readByte, "I", "Read a byte from a specified offset" },
  95	{ "r/2", _readHalfword, "I", "Read a halfword from a specified offset" },
  96	{ "r/4", _readWord, "I", "Read a word from a specified offset" },
  97	{ "set", _setSymbol, "SI", "Assign a symbol to an address" },
  98	{ "stack", _setStackTraceMode, "S", "Change the stack tracing mode" },
  99	{ "status", _printStatus, "", "Print the current status" },
 100	{ "symbol", _findSymbol, "I", "Find the symbol name for an address" },
 101	{ "trace", _trace, "Is", "Trace a number of instructions" },
 102	{ "w/1", _writeByte, "II", "Write a byte at a specified offset" },
 103	{ "w/2", _writeHalfword, "II", "Write a halfword at a specified offset" },
 104	{ "w/r", _writeRegister, "SI", "Write a register" },
 105	{ "w/4", _writeWord, "II", "Write a word at a specified offset" },
 106	{ "watch", _setReadWriteWatchpoint, "Is", "Set a watchpoint" },
 107	{ "watch/c", _setWriteChangedWatchpoint, "Is", "Set a change watchpoint" },
 108	{ "watch/r", _setReadWatchpoint, "Is", "Set a read watchpoint" },
 109	{ "watch/w", _setWriteWatchpoint, "Is", "Set a write watchpoint" },
 110	{ "x/1", _dumpByte, "Ii", "Examine bytes at a specified offset" },
 111	{ "x/2", _dumpHalfword, "Ii", "Examine halfwords at a specified offset" },
 112	{ "x/4", _dumpWord, "Ii", "Examine words at a specified offset" },
 113#ifdef ENABLE_SCRIPTING
 114	{ "source", _source, "S", "Load a script" },
 115#endif
 116#if !defined(NDEBUG) && !defined(_WIN32)
 117	{ "!", _breakInto, "", "Break into attached debugger (for developers)" },
 118#endif
 119	{ 0, 0, 0, 0 }
 120};
 121
 122static struct CLIDebuggerCommandAlias _debuggerCommandAliases[] = {
 123	{ "b", "break" },
 124	{ "bt", "backtrace" },
 125	{ "c", "continue" },
 126	{ "d", "delete" },
 127	{ "dis", "disassemble" },
 128	{ "disasm", "disassemble" },
 129	{ "h", "help" },
 130	{ "i", "status" },
 131	{ "info", "status" },
 132	{ "lb", "listb" },
 133	{ "lw", "listw" },
 134	{ "n", "next" },
 135	{ "p", "print" },
 136	{ "p/t", "print/t" },
 137	{ "p/x", "print/x" },
 138	{ "q", "quit" },
 139	{ "w", "watch" },
 140	{ ".", "source" },
 141	{ 0, 0 }
 142};
 143
 144#if !defined(NDEBUG) && !defined(_WIN32)
 145static void _handleDeath(int sig) {
 146	UNUSED(sig);
 147	printf("No debugger attached!\n");
 148}
 149
 150static void _breakInto(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
 151	UNUSED(debugger);
 152	UNUSED(dv);
 153	struct sigaction sa, osa;
 154	sa.sa_handler = _handleDeath;
 155	sigemptyset(&sa.sa_mask);
 156	sigaddset(&sa.sa_mask, SIGTRAP);
 157	sa.sa_flags = SA_RESTART;
 158	sigaction(SIGTRAP, &sa, &osa);
 159#ifdef USE_PTHREADS
 160	pthread_kill(pthread_self(), SIGTRAP);
 161#else
 162	kill(getpid(), SIGTRAP);
 163#endif
 164	sigaction(SIGTRAP, &osa, 0);
 165}
 166#endif
 167
 168static bool CLIDebuggerCheckTraceMode(struct CLIDebugger* debugger, bool requireEnabled) {
 169	struct mDebuggerPlatform* platform = debugger->d.platform;
 170	if (!platform->getStackTraceMode) {
 171		debugger->backend->printf(debugger->backend, "Stack tracing is not supported by this platform.\n");
 172		return false;
 173	} else if (requireEnabled && platform->getStackTraceMode(platform) == STACK_TRACE_DISABLED) {
 174		debugger->backend->printf(debugger->backend, "Stack tracing is not enabled.\n");
 175		return false;
 176	}
 177	return true;
 178}
 179
 180static void _continue(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
 181	UNUSED(dv);
 182	debugger->d.state = debugger->traceRemaining != 0 ? DEBUGGER_CALLBACK : DEBUGGER_RUNNING;
 183}
 184
 185static void _next(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
 186	UNUSED(dv);
 187	struct mDebuggerPlatform* platform = debugger->d.platform;
 188	debugger->d.core->step(debugger->d.core);
 189	if (platform->getStackTraceMode && platform->getStackTraceMode(platform) != STACK_TRACE_DISABLED) {
 190		platform->updateStackTrace(platform);
 191	}
 192	_printStatus(debugger, 0);
 193}
 194
 195static void _disassemble(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
 196	debugger->system->disassemble(debugger->system, dv);
 197}
 198
 199static bool _parseExpression(struct mDebugger* debugger, struct CLIDebugVector* dv, int32_t* intValue, int* segmentValue) {
 200	size_t args = 0;
 201	struct CLIDebugVector* accum;
 202	for (accum = dv; accum; accum = accum->next) {
 203		++args;
 204	}
 205	const char** arglist = calloc(args + 1, sizeof(const char*));
 206	args = 0;
 207	for (accum = dv; accum; accum = accum->next) {
 208		arglist[args] = accum->charValue;
 209		++args;
 210	}
 211	arglist[args] = NULL;
 212	struct ParseTree* tree = _parseTree(arglist);
 213	free(arglist);
 214
 215	if (!tree) {
 216		return false;
 217	}
 218	if (!mDebuggerEvaluateParseTree(debugger, tree, intValue, segmentValue)) {
 219		parseFree(tree);
 220		free(tree);
 221		return false;
 222	}
 223	parseFree(tree);
 224	free(tree);
 225	return true;
 226}
 227
 228static void _print(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
 229	int32_t intValue = 0;
 230	int segmentValue = -1;
 231	if (!_parseExpression(&debugger->d, dv, &intValue, &segmentValue)) {
 232		debugger->backend->printf(debugger->backend, "Parse error\n");
 233		return;
 234	}
 235	if (segmentValue >= 0) {
 236		debugger->backend->printf(debugger->backend, " $%02X:%04X\n", segmentValue, intValue);
 237	} else {
 238		debugger->backend->printf(debugger->backend, " %u\n", intValue);
 239	}
 240}
 241
 242static void _printBin(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
 243	int32_t intValue = 0;
 244	int segmentValue = -1;
 245	if (!_parseExpression(&debugger->d, dv, &intValue, &segmentValue)) {
 246		debugger->backend->printf(debugger->backend, "Parse error\n");
 247		return;
 248	}
 249	debugger->backend->printf(debugger->backend, " 0b");
 250	int i = 32;
 251	while (i--) {
 252		debugger->backend->printf(debugger->backend, "%u", (intValue >> i) & 1);
 253	}
 254	debugger->backend->printf(debugger->backend, "\n");
 255}
 256
 257static void _printHex(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
 258	int32_t intValue = 0;
 259	int segmentValue = -1;
 260	if (!_parseExpression(&debugger->d, dv, &intValue, &segmentValue)) {
 261		debugger->backend->printf(debugger->backend, "Parse error\n");
 262		return;
 263	}
 264	debugger->backend->printf(debugger->backend, " 0x%08X\n", intValue);
 265}
 266
 267static void _printCommands(struct CLIDebugger* debugger, struct CLIDebuggerCommandSummary* commands, struct CLIDebuggerCommandAlias* aliases) {
 268	int i;
 269	for (i = 0; commands[i].name; ++i) {
 270		debugger->backend->printf(debugger->backend, "%-15s  %s\n", commands[i].name, commands[i].summary);
 271		if (aliases) {
 272			bool printedAlias = false;
 273			int j;
 274			for (j = 0; aliases[j].name; ++j) {
 275				if (strcmp(aliases[j].original, commands[i].name) == 0) {
 276					if (!printedAlias) {
 277						debugger->backend->printf(debugger->backend, "                 Aliases:");
 278						printedAlias = true;
 279					}
 280					debugger->backend->printf(debugger->backend, " %s", aliases[j].name);
 281				}
 282			}
 283			if (printedAlias) {
 284				debugger->backend->printf(debugger->backend, "\n");
 285			}
 286		}
 287	}
 288}
 289
 290static void _printCommandSummary(struct CLIDebugger* debugger, const char* name, struct CLIDebuggerCommandSummary* commands, struct CLIDebuggerCommandAlias* aliases) {
 291	int i;
 292	for (i = 0; commands[i].name; ++i) {
 293		if (strcmp(commands[i].name, name) == 0) {
 294			debugger->backend->printf(debugger->backend, " %s\n", commands[i].summary);
 295			if (aliases) {
 296				bool printedAlias = false;
 297				int j;
 298				for (j = 0; aliases[j].name; ++j) {
 299					if (strcmp(aliases[j].original, commands[i].name) == 0) {
 300						if (!printedAlias) {
 301							debugger->backend->printf(debugger->backend, " Aliases:");
 302							printedAlias = true;
 303						}
 304						debugger->backend->printf(debugger->backend, " %s", aliases[j].name);
 305					}
 306				}
 307				if (printedAlias) {
 308					debugger->backend->printf(debugger->backend, "\n");
 309				}
 310			}
 311			return;
 312		}
 313	}
 314}
 315
 316static void _printHelp(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
 317	UNUSED(dv);
 318	if (!dv) {
 319		debugger->backend->printf(debugger->backend, "Generic commands:\n");
 320		_printCommands(debugger, _debuggerCommands, _debuggerCommandAliases);
 321		if (debugger->system) {
 322			debugger->backend->printf(debugger->backend, "\n%s commands:\n", debugger->system->platformName);
 323			_printCommands(debugger, debugger->system->platformCommands, debugger->system->platformCommandAliases);
 324			debugger->backend->printf(debugger->backend, "\n%s commands:\n", debugger->system->name);
 325			_printCommands(debugger, debugger->system->commands, debugger->system->commandAliases);
 326		}
 327	} else {
 328		_printCommandSummary(debugger, dv->charValue, _debuggerCommands, _debuggerCommandAliases);
 329		if (debugger->system) {
 330			_printCommandSummary(debugger, dv->charValue, debugger->system->platformCommands, debugger->system->platformCommandAliases);
 331			_printCommandSummary(debugger, dv->charValue, debugger->system->commands, debugger->system->commandAliases);
 332		}
 333	}
 334}
 335
 336static void _quit(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
 337	UNUSED(dv);
 338	debugger->d.state = DEBUGGER_SHUTDOWN;
 339}
 340
 341static void _readByte(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
 342	if (!dv || dv->type != CLIDV_INT_TYPE) {
 343		debugger->backend->printf(debugger->backend, "%s\n", ERROR_MISSING_ARGS);
 344		return;
 345	}
 346	uint32_t address = dv->intValue;
 347	uint8_t value;
 348	if (dv->segmentValue >= 0) {
 349		value = debugger->d.core->rawRead8(debugger->d.core, address, dv->segmentValue);
 350	} else {
 351		value = debugger->d.core->busRead8(debugger->d.core, address);
 352	}
 353	debugger->backend->printf(debugger->backend, " 0x%02X\n", value);
 354}
 355
 356static void _reset(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
 357	UNUSED(dv);
 358	mStackTraceClear(&debugger->d.stackTrace);
 359	debugger->d.core->reset(debugger->d.core);
 360	_printStatus(debugger, 0);
 361}
 362
 363static void _readHalfword(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
 364	if (!dv || dv->type != CLIDV_INT_TYPE) {
 365		debugger->backend->printf(debugger->backend, "%s\n", ERROR_MISSING_ARGS);
 366		return;
 367	}
 368	uint32_t address = dv->intValue;
 369	uint16_t value;
 370	if (dv->segmentValue >= 0) {
 371		value = debugger->d.core->rawRead16(debugger->d.core, address & -1, dv->segmentValue);
 372	} else {
 373		value = debugger->d.core->busRead16(debugger->d.core, address & ~1);
 374	}
 375	debugger->backend->printf(debugger->backend, " 0x%04X\n", value);
 376}
 377
 378static void _readWord(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
 379	if (!dv || dv->type != CLIDV_INT_TYPE) {
 380		debugger->backend->printf(debugger->backend, "%s\n", ERROR_MISSING_ARGS);
 381		return;
 382	}
 383	uint32_t address = dv->intValue;
 384	uint32_t value;
 385	if (dv->segmentValue >= 0) {
 386		value = debugger->d.core->rawRead32(debugger->d.core, address & -3, dv->segmentValue);
 387	} else {
 388		value = debugger->d.core->busRead32(debugger->d.core, address & ~3);
 389	}
 390	debugger->backend->printf(debugger->backend, " 0x%08X\n", value);
 391}
 392
 393static void _writeByte(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
 394	if (!dv || !dv->next) {
 395		debugger->backend->printf(debugger->backend, "%s\n", ERROR_MISSING_ARGS);
 396		return;
 397	}
 398	if (dv->type != CLIDV_INT_TYPE || dv->next->type != CLIDV_INT_TYPE) {
 399		debugger->backend->printf(debugger->backend, "%s\n", ERROR_INVALID_ARGS);
 400		return;
 401	}
 402	uint32_t address = dv->intValue;
 403	uint32_t value = dv->next->intValue;
 404	if (value > 0xFF) {
 405		debugger->backend->printf(debugger->backend, "%s\n", ERROR_OVERFLOW);
 406		return;
 407	}
 408	if (dv->segmentValue >= 0) {
 409		debugger->d.core->rawWrite8(debugger->d.core, address, value, dv->segmentValue);
 410	} else {
 411		debugger->d.core->busWrite8(debugger->d.core, address, value);
 412	}
 413}
 414
 415static void _writeHalfword(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
 416	if (!dv || !dv->next) {
 417		debugger->backend->printf(debugger->backend, "%s\n", ERROR_MISSING_ARGS);
 418		return;
 419	}
 420	if (dv->type != CLIDV_INT_TYPE || dv->next->type != CLIDV_INT_TYPE) {
 421		debugger->backend->printf(debugger->backend, "%s\n", ERROR_INVALID_ARGS);
 422		return;
 423	}
 424	uint32_t address = dv->intValue;
 425	uint32_t value = dv->next->intValue;
 426	if (value > 0xFFFF) {
 427		debugger->backend->printf(debugger->backend, "%s\n", ERROR_OVERFLOW);
 428		return;
 429	}
 430	if (dv->segmentValue >= 0) {
 431		debugger->d.core->rawWrite16(debugger->d.core, address, value, dv->segmentValue);
 432	} else {
 433		debugger->d.core->busWrite16(debugger->d.core, address, value);
 434	}
 435}
 436
 437static void _writeRegister(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
 438	if (!dv || !dv->next) {
 439		debugger->backend->printf(debugger->backend, "%s\n", ERROR_MISSING_ARGS);
 440		return;
 441	}
 442	if (dv->type != CLIDV_CHAR_TYPE || dv->next->type != CLIDV_INT_TYPE) {
 443		debugger->backend->printf(debugger->backend, "%s\n", ERROR_INVALID_ARGS);
 444		return;
 445	}
 446	if (!debugger->d.platform->setRegister(debugger->d.platform, dv->charValue, dv->next->intValue)) {
 447		debugger->backend->printf(debugger->backend, "%s\n", ERROR_INVALID_ARGS);
 448	}
 449}
 450
 451static void _writeWord(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
 452	if (!dv || !dv->next) {
 453		debugger->backend->printf(debugger->backend, "%s\n", ERROR_MISSING_ARGS);
 454		return;
 455	}
 456	if (dv->type != CLIDV_INT_TYPE || dv->next->type != CLIDV_INT_TYPE) {
 457		debugger->backend->printf(debugger->backend, "%s\n", ERROR_INVALID_ARGS);
 458		return;
 459	}
 460	uint32_t address = dv->intValue;
 461	uint32_t value = dv->next->intValue;
 462	if (dv->segmentValue >= 0) {
 463		debugger->d.core->rawWrite32(debugger->d.core, address, value, dv->segmentValue);
 464	} else {
 465		debugger->d.core->busWrite32(debugger->d.core, address, value);
 466	}
 467}
 468
 469static void _dumpByte(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
 470	if (!dv || dv->type != CLIDV_INT_TYPE) {
 471		debugger->backend->printf(debugger->backend, "%s\n", ERROR_MISSING_ARGS);
 472		return;
 473	}
 474	uint32_t address = dv->intValue;
 475	uint32_t words = 16;
 476	if (dv->next && dv->next->type == CLIDV_INT_TYPE) {
 477		words = dv->next->intValue;
 478	}
 479	while (words) {
 480		uint32_t line = 16;
 481		if (line > words) {
 482			line = words;
 483		}
 484		debugger->backend->printf(debugger->backend, "0x%08X:", address);
 485		for (; line > 0; --line, ++address, --words) {
 486			uint32_t value;
 487			if (dv->segmentValue >= 0) {
 488				value = debugger->d.core->rawRead8(debugger->d.core, address, dv->segmentValue);
 489			} else {
 490				value = debugger->d.core->busRead8(debugger->d.core, address);
 491			}
 492			debugger->backend->printf(debugger->backend, " %02X", value);
 493		}
 494		debugger->backend->printf(debugger->backend, "\n");
 495	}
 496}
 497
 498static void _dumpHalfword(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
 499	if (!dv || dv->type != CLIDV_INT_TYPE) {
 500		debugger->backend->printf(debugger->backend, "%s\n", ERROR_MISSING_ARGS);
 501		return;
 502	}
 503	uint32_t address = dv->intValue;
 504	uint32_t words = 8;
 505	if (dv->next && dv->next->type == CLIDV_INT_TYPE) {
 506		words = dv->next->intValue;
 507	}
 508	while (words) {
 509		uint32_t line = 8;
 510		if (line > words) {
 511			line = words;
 512		}
 513		debugger->backend->printf(debugger->backend, "0x%08X:", address);
 514		for (; line > 0; --line, address += 2, --words) {
 515			uint32_t value;
 516			if (dv->segmentValue >= 0) {
 517				value = debugger->d.core->rawRead16(debugger->d.core, address, dv->segmentValue);
 518			} else {
 519				value = debugger->d.core->busRead16(debugger->d.core, address);
 520			}
 521			debugger->backend->printf(debugger->backend, " %04X", value);
 522		}
 523		debugger->backend->printf(debugger->backend, "\n");
 524	}
 525}
 526
 527static void _dumpWord(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
 528	if (!dv || dv->type != CLIDV_INT_TYPE) {
 529		debugger->backend->printf(debugger->backend, "%s\n", ERROR_MISSING_ARGS);
 530		return;
 531	}
 532	uint32_t address = dv->intValue;
 533	uint32_t words = 4;
 534	if (dv->next && dv->next->type == CLIDV_INT_TYPE) {
 535		words = dv->next->intValue;
 536	}
 537	while (words) {
 538		uint32_t line = 4;
 539		if (line > words) {
 540			line = words;
 541		}
 542		debugger->backend->printf(debugger->backend, "0x%08X:", address);
 543		for (; line > 0; --line, address += 4, --words) {
 544			uint32_t value;
 545			if (dv->segmentValue >= 0) {
 546				value = debugger->d.core->rawRead32(debugger->d.core, address, dv->segmentValue);
 547			} else {
 548				value = debugger->d.core->busRead32(debugger->d.core, address);
 549			}
 550			debugger->backend->printf(debugger->backend, " %08X", value);
 551		}
 552		debugger->backend->printf(debugger->backend, "\n");
 553	}
 554}
 555
 556#ifdef ENABLE_SCRIPTING
 557static void _source(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
 558	if (!dv) {
 559		debugger->backend->printf(debugger->backend, "Needs a filename\n");
 560		return;
 561	}
 562	if (debugger->d.bridge && mScriptBridgeLoadScript(debugger->d.bridge, dv->charValue)) {
 563		mScriptBridgeRun(debugger->d.bridge);
 564	} else {
 565		debugger->backend->printf(debugger->backend, "Failed to load script\n");
 566	}
 567}
 568#endif
 569
 570static struct ParseTree* _parseTree(const char** string) {
 571	struct LexVector lv;
 572	bool error = false;
 573	LexVectorInit(&lv, 0);
 574	size_t i;
 575	for (i = 0; string[i]; ++i) {
 576		size_t length = strlen(string[i]);
 577		size_t adjusted = lexExpression(&lv, string[i], length, NULL);
 578		if (!adjusted || adjusted > length) {
 579			error = true;
 580		}
 581	}
 582	struct ParseTree* tree = NULL;
 583	if (!error) {
 584		tree = malloc(sizeof(*tree));
 585		parseLexedExpression(tree, &lv);
 586	}
 587	lexFree(&lv);
 588	LexVectorClear(&lv);
 589	LexVectorDeinit(&lv);
 590	if (error) {
 591		if (tree) {
 592			parseFree(tree);
 593			free(tree);
 594		}
 595		return NULL;
 596	} else {
 597		return tree;
 598	}
 599}
 600
 601static void _setBreakpoint(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
 602	if (!dv || dv->type != CLIDV_INT_TYPE) {
 603		debugger->backend->printf(debugger->backend, "%s\n", ERROR_MISSING_ARGS);
 604		return;
 605	}
 606	struct mBreakpoint breakpoint = {
 607		.address = dv->intValue,
 608		.segment = dv->segmentValue,
 609		.type = BREAKPOINT_HARDWARE
 610	};
 611	if (dv->next && dv->next->type == CLIDV_CHAR_TYPE) {
 612		struct ParseTree* tree = _parseTree((const char*[]) { dv->next->charValue, NULL });
 613		if (tree) {
 614			breakpoint.condition = tree;
 615		} else {
 616			debugger->backend->printf(debugger->backend, "%s\n", ERROR_INVALID_ARGS);
 617			return;
 618		}
 619	}
 620	ssize_t id = debugger->d.platform->setBreakpoint(debugger->d.platform, &breakpoint);
 621	if (id > 0) {
 622		debugger->backend->printf(debugger->backend, INFO_BREAKPOINT_ADDED, id);
 623	}
 624}
 625
 626static void _setWatchpoint(struct CLIDebugger* debugger, struct CLIDebugVector* dv, enum mWatchpointType type) {
 627	if (!dv || dv->type != CLIDV_INT_TYPE) {
 628		debugger->backend->printf(debugger->backend, "%s\n", ERROR_MISSING_ARGS);
 629		return;
 630	}
 631	if (!debugger->d.platform->setWatchpoint) {
 632		debugger->backend->printf(debugger->backend, "Watchpoints are not supported by this platform.\n");
 633		return;
 634	}
 635	struct mWatchpoint watchpoint = {
 636		.address = dv->intValue,
 637		.segment = dv->segmentValue,
 638		.type = type
 639	};
 640	if (dv->next && dv->next->type == CLIDV_CHAR_TYPE) {
 641		struct ParseTree* tree = _parseTree((const char*[]) { dv->next->charValue, NULL });
 642		if (tree) {
 643			watchpoint.condition = tree;
 644		} else {
 645			debugger->backend->printf(debugger->backend, "%s\n", ERROR_INVALID_ARGS);
 646			return;
 647		}
 648	}
 649	ssize_t id = debugger->d.platform->setWatchpoint(debugger->d.platform, &watchpoint);
 650	if (id > 0) {
 651		debugger->backend->printf(debugger->backend, INFO_WATCHPOINT_ADDED, id);
 652	}
 653}
 654
 655static void _setReadWriteWatchpoint(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
 656	_setWatchpoint(debugger, dv, WATCHPOINT_RW);
 657}
 658
 659static void _setReadWatchpoint(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
 660	_setWatchpoint(debugger, dv, WATCHPOINT_READ);
 661}
 662
 663static void _setWriteWatchpoint(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
 664	_setWatchpoint(debugger, dv, WATCHPOINT_WRITE);
 665}
 666
 667static void _setWriteChangedWatchpoint(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
 668	_setWatchpoint(debugger, dv, WATCHPOINT_WRITE_CHANGE);
 669}
 670
 671static void _clearBreakpoint(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
 672	if (!dv || dv->type != CLIDV_INT_TYPE) {
 673		debugger->backend->printf(debugger->backend, "%s\n", ERROR_MISSING_ARGS);
 674		return;
 675	}
 676	uint64_t id = dv->intValue;
 677	debugger->d.platform->clearBreakpoint(debugger->d.platform, id);
 678}
 679
 680static void _listBreakpoints(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
 681	UNUSED(dv);
 682	struct mBreakpointList breakpoints;
 683	mBreakpointListInit(&breakpoints, 0);
 684	debugger->d.platform->listBreakpoints(debugger->d.platform, &breakpoints);
 685	size_t i;
 686	for (i = 0; i < mBreakpointListSize(&breakpoints); ++i) {
 687		struct mBreakpoint* breakpoint = mBreakpointListGetPointer(&breakpoints, i);
 688		if (breakpoint->segment >= 0) {
 689			debugger->backend->printf(debugger->backend, "%" PRIz "i: %02X:%X\n", breakpoint->id, breakpoint->segment, breakpoint->address);
 690		} else {
 691			debugger->backend->printf(debugger->backend, "%" PRIz "i: 0x%X\n", breakpoint->id, breakpoint->address);
 692		}
 693	}
 694	mBreakpointListDeinit(&breakpoints);
 695}
 696
 697static void _listWatchpoints(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
 698	UNUSED(dv);
 699	struct mWatchpointList watchpoints;
 700	mWatchpointListInit(&watchpoints, 0);
 701	debugger->d.platform->listWatchpoints(debugger->d.platform, &watchpoints);
 702	size_t i;
 703	for (i = 0; i < mWatchpointListSize(&watchpoints); ++i) {
 704		struct mWatchpoint* watchpoint = mWatchpointListGetPointer(&watchpoints, i);
 705		if (watchpoint->segment >= 0) {
 706			debugger->backend->printf(debugger->backend, "%" PRIz "i: %02X:%X\n", watchpoint->id, watchpoint->segment, watchpoint->address);
 707		} else {
 708			debugger->backend->printf(debugger->backend, "%" PRIz "i: 0x%X\n", watchpoint->id, watchpoint->address);
 709		}
 710	}
 711	mWatchpointListDeinit(&watchpoints);
 712}
 713
 714static void _trace(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
 715	if (!dv || dv->type != CLIDV_INT_TYPE) {
 716		debugger->backend->printf(debugger->backend, "%s\n", ERROR_MISSING_ARGS);
 717		return;
 718	}
 719
 720	debugger->traceRemaining = dv->intValue;
 721	if (debugger->traceVf) {
 722		debugger->traceVf->close(debugger->traceVf);
 723		debugger->traceVf = NULL;
 724	}
 725	if (debugger->traceRemaining == 0) {
 726		return;
 727	}
 728	if (dv->next && dv->next->charValue) {
 729		debugger->traceVf = VFileOpen(dv->next->charValue, O_CREAT | O_WRONLY | O_APPEND);
 730	}
 731	if (_doTrace(debugger)) {
 732		debugger->d.state = DEBUGGER_CALLBACK;
 733	} else {
 734		debugger->system->printStatus(debugger->system);
 735	}
 736}
 737
 738static bool _doTrace(struct CLIDebugger* debugger) {
 739	char trace[1024];
 740	trace[sizeof(trace) - 1] = '\0';
 741	size_t traceSize = sizeof(trace) - 2;
 742	debugger->d.platform->trace(debugger->d.platform, trace, &traceSize);
 743	if (traceSize + 1 <= sizeof(trace)) {
 744		trace[traceSize] = '\n';
 745		trace[traceSize + 1] = '\0';
 746	}
 747	if (debugger->traceVf) {
 748		debugger->traceVf->write(debugger->traceVf, trace, traceSize + 1);
 749	} else {
 750		debugger->backend->printf(debugger->backend, "%s", trace);
 751	}
 752	if (debugger->traceRemaining > 0) {
 753		--debugger->traceRemaining;
 754	}
 755	return debugger->traceRemaining != 0;
 756}
 757
 758static void _printStatus(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
 759	UNUSED(dv);
 760	debugger->system->printStatus(debugger->system);
 761}
 762
 763struct CLIDebugVector* CLIDVParse(struct CLIDebugger* debugger, const char* string, size_t length) {
 764	if (!string || length < 1) {
 765		return 0;
 766	}
 767
 768	struct CLIDebugVector dvTemp = { .type = CLIDV_INT_TYPE, .segmentValue = -1 };
 769
 770	struct LexVector lv;
 771	LexVectorInit(&lv, 0);
 772	size_t adjusted = lexExpression(&lv, string, length, " ");
 773	if (adjusted > length) {
 774		dvTemp.type = CLIDV_ERROR_TYPE;
 775	}
 776
 777	struct ParseTree tree;
 778	parseLexedExpression(&tree, &lv);
 779	if (tree.token.type == TOKEN_ERROR_TYPE) {
 780		dvTemp.type = CLIDV_ERROR_TYPE;
 781	} else {
 782		if (!mDebuggerEvaluateParseTree(&debugger->d, &tree, &dvTemp.intValue, &dvTemp.segmentValue)) {
 783			dvTemp.type = CLIDV_ERROR_TYPE;
 784		}
 785	}
 786
 787	parseFree(&tree);
 788
 789	lexFree(&lv);
 790	LexVectorDeinit(&lv);
 791
 792	struct CLIDebugVector* dv = malloc(sizeof(struct CLIDebugVector));
 793	if (dvTemp.type == CLIDV_ERROR_TYPE) {
 794		dv->type = CLIDV_ERROR_TYPE;
 795		dv->next = 0;
 796	} else {
 797		*dv = dvTemp;
 798	}
 799	return dv;
 800}
 801
 802struct CLIDebugVector* CLIDVStringParse(struct CLIDebugger* debugger, const char* string, size_t length) {
 803	UNUSED(debugger);
 804	if (!string || length < 1) {
 805		return 0;
 806	}
 807
 808	struct CLIDebugVector dvTemp = { .type = CLIDV_CHAR_TYPE };
 809
 810	dvTemp.charValue = strndup(string, length);
 811
 812	struct CLIDebugVector* dv = malloc(sizeof(struct CLIDebugVector));
 813	*dv = dvTemp;
 814	return dv;
 815}
 816
 817static void _DVFree(struct CLIDebugVector* dv) {
 818	struct CLIDebugVector* next;
 819	while (dv) {
 820		next = dv->next;
 821		if (dv->type == CLIDV_CHAR_TYPE) {
 822			free(dv->charValue);
 823		}
 824		free(dv);
 825		dv = next;
 826	}
 827}
 828
 829static struct CLIDebugVector* _parseArg(struct CLIDebugger* debugger, const char* args, size_t argsLen, char type) {
 830	struct CLIDebugVector* dv = NULL;
 831	switch (type) {
 832	case 'I':
 833	case 'i':
 834		return CLIDVParse(debugger, args, argsLen);
 835	case 'S':
 836	case 's':
 837		return CLIDVStringParse(debugger, args, argsLen);
 838	case '*':
 839		dv = _parseArg(debugger, args, argsLen, 'I');
 840		if (!dv) {
 841			dv = _parseArg(debugger, args, argsLen, 'S');
 842		}
 843		break;
 844	}
 845	return dv;
 846}
 847
 848static int _tryCommands(struct CLIDebugger* debugger, struct CLIDebuggerCommandSummary* commands, struct CLIDebuggerCommandAlias* aliases, const char* command, size_t commandLen, const char* args, size_t argsLen) {
 849	struct CLIDebugVector* dv = NULL;
 850	struct CLIDebugVector* dvLast = NULL;
 851	int i;
 852	const char* name;
 853	if (aliases) {
 854		for (i = 0; (name = aliases[i].name); ++i) {
 855			if (strlen(name) != commandLen) {
 856				continue;
 857			}
 858			if (strncasecmp(name, command, commandLen) == 0) {
 859				command = aliases[i].original;
 860				commandLen = strlen(aliases[i].original);
 861			}
 862		}
 863	}
 864	for (i = 0; (name = commands[i].name); ++i) {
 865		if (strlen(name) != commandLen) {
 866			continue;
 867		}
 868		if (strncasecmp(name, command, commandLen) == 0) {
 869			if (commands[i].format && args) {
 870				char lastArg = '\0';
 871				int arg;
 872				for (arg = 0; commands[i].format[arg] && argsLen; ++arg) {
 873					while (isspace(args[0]) && argsLen) {
 874						++args;
 875						--argsLen;
 876					}
 877					if (!args[0] || !argsLen) {
 878						debugger->backend->printf(debugger->backend, "Wrong number of arguments\n");
 879						_DVFree(dv);
 880						return 0;
 881					}
 882
 883					size_t adjusted;
 884					const char* next = strchr(args, ' ');
 885					if (next) {
 886						adjusted = next - args;
 887					} else {
 888						adjusted = argsLen;
 889					}
 890
 891					struct CLIDebugVector* dvNext = NULL;
 892					bool nextArgMandatory = false;
 893
 894					if (commands[i].format[arg] == '+') {
 895						dvNext = _parseArg(debugger, args, adjusted, lastArg);
 896						--arg;
 897					} else {
 898						nextArgMandatory = isupper(commands[i].format[arg]) || (commands[i].format[arg] == '*');
 899						dvNext = _parseArg(debugger, args, adjusted, commands[i].format[arg]);
 900						lastArg = commands[i].format[arg];
 901					}
 902
 903					args += adjusted;
 904					argsLen -= adjusted;
 905
 906					if (!dvNext) {
 907						if (!nextArgMandatory) {
 908							args = NULL;
 909						}
 910						break;
 911					}
 912					if (dvNext->type == CLIDV_ERROR_TYPE) {
 913						debugger->backend->printf(debugger->backend, "Parse error\n");
 914						_DVFree(dv);
 915						_DVFree(dvNext);
 916						return 0;
 917					}
 918
 919					if (dvLast) {
 920						dvLast->next = dvNext;
 921						dvLast = dvNext;
 922					} else {
 923						dv = dvNext;
 924						dvLast = dv;
 925					}
 926				}
 927			}
 928
 929			if (args) {
 930				while (isspace(args[0]) && argsLen) {
 931					++args;
 932					--argsLen;
 933				}
 934			}
 935			if (args && argsLen) {
 936				debugger->backend->printf(debugger->backend, "Wrong number of arguments\n");
 937				_DVFree(dv);
 938				return 0;
 939			}
 940			commands[i].command(debugger, dv);
 941			_DVFree(dv);
 942			return 1;
 943		}
 944	}
 945	return -1;
 946}
 947
 948bool CLIDebuggerRunCommand(struct CLIDebugger* debugger, const char* line, size_t count) {
 949	const char* firstSpace = strchr(line, ' ');
 950	size_t cmdLength;
 951	if (firstSpace) {
 952		cmdLength = firstSpace - line;
 953	} else {
 954		cmdLength = count;
 955	}
 956
 957	const char* args = 0;
 958	if (firstSpace) {
 959		args = firstSpace + 1;
 960	}
 961	int result = _tryCommands(debugger, _debuggerCommands, _debuggerCommandAliases, line, cmdLength, args, count - cmdLength - 1);
 962	if (result < 0 && debugger->system) {
 963		result = _tryCommands(debugger, debugger->system->commands, debugger->system->commandAliases, line, cmdLength, args, count - cmdLength - 1);
 964		if (result < 0) {
 965			result = _tryCommands(debugger, debugger->system->platformCommands, debugger->system->platformCommandAliases, line, cmdLength, args, count - cmdLength - 1);
 966		}
 967	}
 968	if (result < 0) {
 969		debugger->backend->printf(debugger->backend, "Command not found\n");
 970	}
 971	return false;
 972}
 973
 974static void _commandLine(struct mDebugger* debugger) {
 975	struct CLIDebugger* cliDebugger = (struct CLIDebugger*) debugger;
 976	const char* line;
 977		size_t len;
 978	_printStatus(cliDebugger, 0);
 979	while (debugger->state == DEBUGGER_PAUSED) {
 980		line = cliDebugger->backend->readline(cliDebugger->backend, &len);
 981		if (!line || len == 0) {
 982			debugger->state = DEBUGGER_SHUTDOWN;
 983			return;
 984		}
 985		if (line[0] == '\n') {
 986			line = cliDebugger->backend->historyLast(cliDebugger->backend, &len);
 987			if (line && len) {
 988				CLIDebuggerRunCommand(cliDebugger, line, len);
 989			}
 990		} else {
 991			CLIDebuggerRunCommand(cliDebugger, line, len);
 992			cliDebugger->backend->historyAppend(cliDebugger->backend, line);
 993		}
 994	}
 995}
 996
 997static void _reportEntry(struct mDebugger* debugger, enum mDebuggerEntryReason reason, struct mDebuggerEntryInfo* info) {
 998	struct CLIDebugger* cliDebugger = (struct CLIDebugger*) debugger;
 999	if (cliDebugger->traceRemaining > 0) {
1000		cliDebugger->traceRemaining = 0;
1001	}
1002	switch (reason) {
1003	case DEBUGGER_ENTER_MANUAL:
1004	case DEBUGGER_ENTER_ATTACHED:
1005		break;
1006	case DEBUGGER_ENTER_BREAKPOINT:
1007		if (info) {
1008			if (info->pointId > 0) {
1009				cliDebugger->backend->printf(cliDebugger->backend, "Hit breakpoint %" PRIz "i at 0x%08X\n", info->pointId, info->address);
1010			} else {
1011				cliDebugger->backend->printf(cliDebugger->backend, "Hit unknown breakpoint at 0x%08X\n", info->address);
1012			}
1013		} else {
1014			cliDebugger->backend->printf(cliDebugger->backend, "Hit breakpoint\n");
1015		}
1016		break;
1017	case DEBUGGER_ENTER_WATCHPOINT:
1018		if (info) {
1019			if (info->type.wp.accessType & WATCHPOINT_WRITE) {
1020				cliDebugger->backend->printf(cliDebugger->backend, "Hit watchpoint %" PRIz "i at 0x%08X: (new value = 0x%08X, old value = 0x%08X)\n", info->pointId, info->address, info->type.wp.newValue, info->type.wp.oldValue);
1021			} else {
1022				cliDebugger->backend->printf(cliDebugger->backend, "Hit watchpoint %" PRIz "i at 0x%08X: (value = 0x%08X)\n", info->pointId, info->address, info->type.wp.oldValue);
1023			}
1024		} else {
1025			cliDebugger->backend->printf(cliDebugger->backend, "Hit watchpoint\n");
1026		}
1027		break;
1028	case DEBUGGER_ENTER_ILLEGAL_OP:
1029		if (info) {
1030			cliDebugger->backend->printf(cliDebugger->backend, "Hit illegal opcode at 0x%08X: 0x%08X\n", info->address, info->type.bp.opcode);
1031		} else {
1032			cliDebugger->backend->printf(cliDebugger->backend, "Hit illegal opcode\n");
1033		}
1034		break;
1035	case DEBUGGER_ENTER_STACK:
1036		if (info) {
1037			if (info->type.st.traceType == STACK_TRACE_BREAK_ON_CALL) {
1038				struct mStackTrace* stack = &cliDebugger->d.stackTrace;
1039				struct mStackFrame* frame = mStackTraceGetFrame(stack, 0);
1040				if (frame->interrupt) {
1041					cliDebugger->backend->printf(cliDebugger->backend, "Hit interrupt at at 0x%08X\n", info->address);
1042				} else {
1043					cliDebugger->backend->printf(cliDebugger->backend, "Hit function call at at 0x%08X\n", info->address);
1044				}
1045			} else {
1046				cliDebugger->backend->printf(cliDebugger->backend, "Hit function return at at 0x%08X\n", info->address);
1047			}
1048		} else {
1049			cliDebugger->backend->printf(cliDebugger->backend, "Hit function call or return\n");
1050		}
1051		_backtrace(cliDebugger, NULL);
1052		break;
1053	}
1054}
1055
1056static void _cliDebuggerInit(struct mDebugger* debugger) {
1057	struct CLIDebugger* cliDebugger = (struct CLIDebugger*) debugger;
1058	cliDebugger->traceRemaining = 0;
1059	cliDebugger->traceVf = NULL;
1060	cliDebugger->backend->init(cliDebugger->backend);
1061}
1062
1063static void _cliDebuggerDeinit(struct mDebugger* debugger) {
1064	struct CLIDebugger* cliDebugger = (struct CLIDebugger*) debugger;
1065	if (cliDebugger->traceVf) {
1066		cliDebugger->traceVf->close(cliDebugger->traceVf);
1067		cliDebugger->traceVf = NULL;
1068	}
1069
1070	if (cliDebugger->system) {
1071		if (cliDebugger->system->deinit) {
1072			cliDebugger->system->deinit(cliDebugger->system);
1073		}
1074		free(cliDebugger->system);
1075		cliDebugger->system = NULL;
1076	}
1077	if (cliDebugger->backend && cliDebugger->backend->deinit) {
1078		cliDebugger->backend->deinit(cliDebugger->backend);
1079		cliDebugger->backend = NULL;
1080	}
1081}
1082
1083static void _cliDebuggerCustom(struct mDebugger* debugger) {
1084	struct CLIDebugger* cliDebugger = (struct CLIDebugger*) debugger;
1085	bool retain = true;
1086	enum mDebuggerState next = DEBUGGER_RUNNING;
1087	if (cliDebugger->traceRemaining) {
1088		retain = _doTrace(cliDebugger) && retain;
1089		next = DEBUGGER_PAUSED;
1090	}
1091	if (cliDebugger->system) {
1092		retain = cliDebugger->system->custom(cliDebugger->system) && retain;
1093	}
1094	if (!retain && debugger->state == DEBUGGER_CALLBACK) {
1095		debugger->state = next;
1096	}
1097}
1098
1099void CLIDebuggerCreate(struct CLIDebugger* debugger) {
1100	debugger->d.init = _cliDebuggerInit;
1101	debugger->d.deinit = _cliDebuggerDeinit;
1102	debugger->d.custom = _cliDebuggerCustom;
1103	debugger->d.paused = _commandLine;
1104	debugger->d.entered = _reportEntry;
1105	debugger->d.type = DEBUGGER_CLI;
1106
1107	debugger->system = NULL;
1108	debugger->backend = NULL;
1109}
1110
1111void CLIDebuggerAttachSystem(struct CLIDebugger* debugger, struct CLIDebuggerSystem* system) {
1112	if (debugger->system) {
1113		if (debugger->system->deinit) {
1114			debugger->system->deinit(debugger->system);
1115		}
1116		free(debugger->system);
1117	}
1118
1119	debugger->system = system;
1120	system->p = debugger;
1121}
1122
1123void CLIDebuggerAttachBackend(struct CLIDebugger* debugger, struct CLIDebuggerBackend* backend) {
1124	if (debugger->backend == backend) {
1125		return;
1126	}
1127	if (debugger->backend && debugger->backend->deinit) {
1128		debugger->backend->deinit(debugger->backend);
1129	}
1130
1131	debugger->backend = backend;
1132	backend->p = debugger;
1133}
1134
1135bool CLIDebuggerTabComplete(struct CLIDebugger* debugger, const char* token, bool initial, size_t tokenLen) {
1136	size_t cmd = 0;
1137	size_t len;
1138	const char* name = 0;
1139	for (len = 1; len <= tokenLen; ++len) {
1140		for (; (name = _debuggerCommands[cmd].name); ++cmd) {
1141			int cmp = strncasecmp(name, token, len);
1142			if (cmp > 0) {
1143				return false;
1144			}
1145			if (cmp == 0) {
1146				break;
1147			}
1148		}
1149	}
1150	if (!name) {
1151		return false;
1152	}
1153	if (_debuggerCommands[cmd + 1].name && strlen(_debuggerCommands[cmd + 1].name) >= len && name[len - 1] == _debuggerCommands[cmd + 1].name[len - 1]) {
1154		--len;
1155		const char* next = 0;
1156		int i;
1157		for (i = cmd + 1; _debuggerCommands[i].name; ++i) {
1158			if (strncasecmp(name, _debuggerCommands[i].name, len)) {
1159				break;
1160			}
1161			next = _debuggerCommands[i].name;
1162		}
1163		if (!next) {
1164			return false;
1165		}
1166
1167		for (; name[len]; ++len) {
1168			if (name[len] != next[len]) {
1169				break;
1170			}
1171			char out[2] = { name[len], '\0' };
1172			debugger->backend->lineAppend(debugger->backend, out);
1173		}
1174		return true;
1175	}
1176	name += len - 1;
1177	debugger->backend->lineAppend(debugger->backend, name);
1178	debugger->backend->lineAppend(debugger->backend, " ");
1179	return true;
1180}
1181
1182static void _backtrace(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
1183	if (!CLIDebuggerCheckTraceMode(debugger, true)) {
1184		return;
1185	}
1186	struct mStackTrace* stack = &debugger->d.stackTrace;
1187	ssize_t frames = mStackTraceGetDepth(stack);
1188	if (dv && dv->type == CLIDV_INT_TYPE && dv->intValue < frames) {
1189		frames = dv->intValue;
1190	}
1191	ssize_t i;
1192	struct mDebuggerSymbols* symbolTable = debugger->d.core->symbolTable;
1193	for (i = 0; i < frames; ++i) {
1194		char trace[1024];
1195		size_t traceSize = sizeof(trace) - 2;
1196		mStackTraceFormatFrame(stack, symbolTable, i, trace, &traceSize);
1197		debugger->backend->printf(debugger->backend, "%s", trace);
1198	}
1199}
1200
1201static void _finish(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
1202	UNUSED(dv);
1203	if (!CLIDebuggerCheckTraceMode(debugger, true)) {
1204		return;
1205	}
1206	struct mStackTrace* stack = &debugger->d.stackTrace;
1207	struct mStackFrame* frame = mStackTraceGetFrame(stack, 0);
1208	if (!frame) {
1209		debugger->backend->printf(debugger->backend, "No current stack frame.\n");
1210		return;
1211	}
1212	frame->breakWhenFinished = true;
1213	_continue(debugger, dv);
1214}
1215
1216static void _setStackTraceMode(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
1217	if (!CLIDebuggerCheckTraceMode(debugger, false)) {
1218		return;
1219	}
1220	if (!dv) {
1221		debugger->backend->printf(debugger->backend, "off           disable stack tracing (default)\n");
1222		debugger->backend->printf(debugger->backend, "trace-only    enable stack tracing\n");
1223		debugger->backend->printf(debugger->backend, "break-call    break on function calls\n");
1224		debugger->backend->printf(debugger->backend, "break-return  break on function returns\n");
1225		debugger->backend->printf(debugger->backend, "break-all     break on function calls and returns\n");
1226		return;
1227	}
1228	if (dv->type != CLIDV_CHAR_TYPE) {
1229		debugger->backend->printf(debugger->backend, "%s\n", ERROR_INVALID_ARGS);
1230		return;
1231	}
1232	struct mDebuggerPlatform* platform = debugger->d.platform;
1233	if (strcmp(dv->charValue, "off") == 0) {
1234		platform->setStackTraceMode(platform, STACK_TRACE_DISABLED);
1235	} else if (strcmp(dv->charValue, "trace-only") == 0) {
1236		platform->setStackTraceMode(platform, STACK_TRACE_ENABLED);
1237	} else if (strcmp(dv->charValue, "break-call") == 0) {
1238		platform->setStackTraceMode(platform, STACK_TRACE_BREAK_ON_CALL);
1239	} else if (strcmp(dv->charValue, "break-return") == 0) {
1240		platform->setStackTraceMode(platform, STACK_TRACE_BREAK_ON_RETURN);
1241	} else if (strcmp(dv->charValue, "break-all") == 0) {
1242		platform->setStackTraceMode(platform, STACK_TRACE_BREAK_ON_BOTH);
1243	} else {
1244		debugger->backend->printf(debugger->backend, "%s\n", ERROR_INVALID_ARGS);
1245	}
1246}
1247
1248static void _setSymbol(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
1249	struct mDebuggerSymbols* symbolTable = debugger->d.core->symbolTable;
1250	if (!symbolTable) {
1251		debugger->backend->printf(debugger->backend, "No symbol table available.\n");
1252		return;
1253	}
1254	if (!dv || !dv->next) {
1255		debugger->backend->printf(debugger->backend, "%s\n", ERROR_MISSING_ARGS);
1256		return;
1257	}
1258	if (dv->type != CLIDV_CHAR_TYPE || dv->next->type != CLIDV_INT_TYPE) {
1259		debugger->backend->printf(debugger->backend, "%s\n", ERROR_INVALID_ARGS);
1260		return;
1261	}
1262	mDebuggerSymbolAdd(symbolTable, dv->charValue, dv->next->intValue, dv->next->segmentValue);
1263}
1264
1265static void _findSymbol(struct CLIDebugger* debugger, struct CLIDebugVector* dv) {
1266	struct mDebuggerSymbols* symbolTable = debugger->d.core->symbolTable;
1267	if (!symbolTable) {
1268		debugger->backend->printf(debugger->backend, "No symbol table available.\n");
1269		return;
1270	}
1271	if (!dv) {
1272		debugger->backend->printf(debugger->backend, "%s\n", ERROR_MISSING_ARGS);
1273		return;
1274	}
1275	if (dv->type != CLIDV_INT_TYPE) {
1276		debugger->backend->printf(debugger->backend, "%s\n", ERROR_INVALID_ARGS);
1277		return;
1278	}
1279	const char* name = mDebuggerSymbolReverseLookup(symbolTable, dv->intValue, dv->segmentValue);
1280	if (name) {
1281		if (dv->segmentValue >= 0) {
1282			debugger->backend->printf(debugger->backend, " 0x%02X:%08X = %s\n", dv->segmentValue, dv->intValue, name);
1283		} else {
1284			debugger->backend->printf(debugger->backend, " 0x%08X = %s\n", dv->intValue, name);
1285		}
1286	} else {
1287		debugger->backend->printf(debugger->backend, "Not found.\n");
1288	}
1289}