--- nono/debugger/debugger.cpp 2026/04/29 17:04:28 1.1 +++ nono/debugger/debugger.cpp 2026/04/29 17:05:13 1.1.1.12 @@ -1,479 +1,1288 @@ // // nono -// Copyright (C) 2019 isaki@NetBSD.org +// Copyright (C) 2020 nono project +// Licensed under nono-license.txt // -#include "header.h" -#include "bus.h" -#include "consio.h" -#include "cvprompt.h" -#include "disasm.h" -#include "m68030core.h" -#include "memdump.h" -#include "mpu.h" +// +// デバッガ +// + +// +// VM スレッド デバッガスレッド HostCOM +// condvar +// | | |<--- 入力 +// | |<----------------------| +// | | RxCallback +// | | +// | |---------------------->| +// | | HostCOMDevice::Tx() |---> 出力 + +// |<---------------------------| +// | is_prompt = true; | デバッガスレッドからプロンプトを出したい +// | Message(MPU_TRACE); | 場合は MPU (VM) をトレースモードにする。 +// | | その際 is_prompt を立てておくことで止まる。 +// | | +// |--------------------------->| +// | condvar REQUEST_PROMPT | VM スレッドからプロンプトを出したい場合 +// | | (上述の例も含む) は条件変数で通知。 +// | | +// |<---------------------------| +// | condvar prompt_released | プロンプトを出している間 VM スレッドは +// | | 条件変数で待機しているので、これを起こす +// | | ことで実行再開。 + +#include "debugger.h" +#include "debugger_private.h" +#include "debugger_m680x0.h" +#include "debugger_m88xx0.h" +#include "hostcom.h" +#include "mainapp.h" #include "mystring.h" -#include +#include "power.h" +#include "scheduler.h" +#include "sync.h" +#include "uimessage.h" +#include "vectortable.h" +#include +#include +#if defined(HAVE_BSD_STDIO_H) +#include +#endif -class Debugger -{ - private: - // 型 - typedef void (Debugger::*cmdfunc_t)(); - typedef struct { - const char *name; - cmdfunc_t func; - } cmddef_t; - - // ブレークポイント - typedef struct { - bool enable; - bool ismemory; - uint32 addr; - uint32 count; - } breakpoint_t; - static const int MAX_BREAKPOINTS = 8; - - public: - Debugger(); - virtual ~Debugger() { } - - void Init(); - void ThreadRun(); - bool Check(); - - private: - bool MainLoop(); - cmddef_t *ParseCmd(); - // コマンド名は大文字小文字を区別する関係でスネークスタイル。 - void cmd_b(); - void cmd_b_list(); - void cmd_brhist(); - void cmd_bx(); - void cmd_c(); - void cmd_d(); - void cmd_dt(); - void cmd_D(); - void cmd_h(); - void cmd_L(); - void cmd_m(); - void cmd_mt(); - void cmd_M(); - void cmd_minus(); - void cmd_n(); - void cmd_q(); - void cmd_r(); - void cmd_ra(); - void cmd_rf(); - void cmd_rm(); - void cmd_ro(); - void cmd_s(); - void cmd_so(); - void cmd_show(); - void cmd_t(); - void cmd_unknown(); - - int AddBreakpoint(uint32 addr, bool ismemory); - void Continue(); - bool GetAddr(uint32& addr, uint32& lastaddr); - void cmd_d_common(MemdumpMode mode); - void cmd_m_common(MemdumpMode mode); - bool ParseAddr(const char *arg, uint32_t *addrp); - const char *OPccCondStr(uint32); - bool IsOPcc(uint16); - bool IsDBcc(uint16); - bool IsCond(uint16); - bool SetNBreakpoint(); - - void HelpMain(); - - void ShowRegMain(); - void ShowRegFPU(); - void ShowRegMMU(); - void ShowRegOther(); - void ShowMonitor(TextScreen& monitor); - - m68kcpu *cpu = NULL; // CPU コア - m68kreg prev {}; // 前回のレジスタセットのコピー - - Consio *cons = NULL; // 入出力 - char cmdbuf[256] {}; // 現在のコマンドライン - char last_cmdbuf[256] {}; // 直前のコマンドライン - int ac = 0; - char *av[10] {}; - - uint32 pc = 0; - uint32 nextpc = 0; - breakpoint_t bpoint[MAX_BREAKPOINTS] {}; - bool bc_enable = false; - uint32 bc_addr = 0; - uint32 d_last_addr = 0; - uint32 m_last_addr = 0; - bool n_enable = false; - bool n_breakenable = false; - uint32 n_breakaddr = 0; - uint32 n_count = 0; - bool s_enable = false; - uint32 s_count = 0; - bool so_enable = false; - uint32 so_a7 = 0; - uint16 so_sr = 0; - bool t_enable = false; - uint32 t_count = 0; +static int readfunc(void *, char *, int); +static int writefunc(void *, const char *, int); - // 一度VMを実行して再びプロンプトに来たら true - bool is_continued = false; +// グローバル参照用 +Debugger *gDebugger; - static cmddef_t cmdtable[]; - static cmddef_t cmdtable_unknown; -}; +// メモリダンプモニタを外部から取得 +Monitor& +debugger_memdump_monitor(int n) +{ + assert(n < MAX_MEMDUMP_MONITOR); + return gDebugger->memdump_monitor[n]; +} -Debugger *gDebugger; -CVPrompt *gCVPrompt; +// コンストラクタ +Debugger::Debugger() + : inherited("Debugger") +{ + // ベクタテーブル + pVectorTable.reset(new VectorTable(gMainApp.GetVMType())); + gVectorTable = pVectorTable.get(); -// コマンドラインオプション -bool debug_on_start; -uint32 debug_breakaddr; + // ブレークポイントモニター + bpoint_monitor.func = ToMonitorCallback(&Debugger::MonitorUpdateBpoint); + bpoint_monitor.SetSize(55, 9); + bpoint_monitor.Regist(ID_MONITOR_BREAKPOINT); -static void *debugger_run(void *); + // メモリダンプモニター + for (int i = 0, end = memdump_monitor.size(); i < end; i++) { + auto& mon = memdump_monitor[i]; + mon.obj = this; + mon.func = ToMonitorCallback(&Debugger::MonitorUpdateMemdump); + mon.SetSize(76, 16); + mon.Regist(ID_MONITOR_MEMDUMP(i)); + } + // m/M コマンド用。こっちは Regist 不要 + m_monitor.func = ToMonitorCallback(&Debugger::MonitorUpdateMemdump); + m_monitor.SetSize(76, 16); +} -// 初期化。 -// この時点で VM が初期化されていること。 -void -debugger_init() +// デストラクタ +Debugger::~Debugger() { - gDebugger = new Debugger(); - gDebugger->Init(); + // fclose(fflush) にあたり hostcom へのアクセスが発生するので、 + // hostcom より先に片付けておかなければならない。 + Close(); - gCVPrompt = new CVPrompt(); + if ((bool)hostcom) { + hostcom->SetCallbackDevice(NULL); + } - // デバッガスレッド起動 - pthread_t th; - pthread_create(&th, NULL, debugger_run, NULL); + TerminateThread(); + gDebugger = NULL; } -// デバッガスレッドのエントリポイント -static void * -debugger_run(void *dummy) +// ログレベル設定 +void +Debugger::SetLogLevel(int loglevel_) { - pthread_setname_np("Debugger"); - pthread_detach(pthread_self()); + inherited::SetLogLevel(loglevel_); - gDebugger->ThreadRun(); - return NULL; + // ホストドライバを従属させる + if ((bool)hostcom) { + hostcom->SetLogLevel(loglevel_); + } } -// コンストラクタ -Debugger::Debugger() +bool +Debugger::Create() { - cpu = gMPU->GetCPU(); + // ホストドライバを作成 + try { + hostcom.reset(new HostCOMDevice("Debugger")); + } catch (...) { + return false; + } + + hostcom->SetRxCallback(ToDeviceCallback(&Debugger::RxCallback)); + hostcom->SetAcceptCallback(ToDeviceCallback(&Debugger::AcceptCallback)); + hostcom->SetCallbackDevice(this); + + return true; } -// コマンドライン引数によって動作を決めるところ。 -// 名前がこれでいいのかはあるけど。 -void +// 初期化 +bool Debugger::Init() { + if (gMPU680x0) { + md.reset(new DebuggerMD_m680x0(this, gMPU680x0->GetCPU())); + } else if (gMPU88xx0) { + md.reset(new DebuggerMD_m88xx0(this, gMPU88xx0->GetCPU())); + } else { + assertmsg(false, "unknown mpu"); + } + // -d なら CPU 起動時点で停止してプロンプトを待つ - if (debug_on_start) { - cpu->atomic_reqflag |= CPU_REQ_PROMPT; + if (gMainApp.debug_on_start) { + is_pause = true; + // この時点ではまだ MPU にメッセージを送ることはできない } // -b ならブレークポイント設定 - if (debug_breakaddr != 0xffffffff) { - cpu->atomic_reqflag |= CPU_REQ_TRACE; - AddBreakpoint(debug_breakaddr, false); + for (auto& str : gMainApp.debug_breakaddr) { + breakpoint_t bp; + + // , で分離できたら を取り出す + int pos = str.find(','); + if (pos != std::string::npos) { + std::string skipstr = str.substr(pos + 1); + bp.skip = atoi(skipstr.c_str()); + + // XXX これ出来るんだっけ? + str[pos] = '\0'; + } + // そしてどちらにしても を取り出す + if (!ParseAddr(str.c_str(), &bp.addr)) { + warnx("\"%s\": Invalid breakpoint address", str.c_str()); + return false; + } + // 登録 + bp.type = BreakpointType::Address; + AddBreakpoint(bp); } - // どこでやるべか - signal(SIGPIPE, SIG_IGN); + // 入出力を FILE で扱う + cons = funopen(this, readfunc, writefunc, NULL, NULL); + if (cons == NULL) { + warnx("funopen2 failed"); + return false; + } + + return true; } // デバッガスレッド void Debugger::ThreadRun() { - // XXX どこかでコンソールの選択とパラメータの取得 - cons = new ConsioTCP(); - if (cons->Init() == false) { - return; - } + // disp_regs の初期値設定。 + // 再接続でも継続してていいような気がするのでループ外で初期化。 + disp_regs.clear(); + disp_regs.push_back("r"); + + // MPU のトレース状態の初期化は vm/mpu* 側のリセット例外で行っている。 for (;;) { - cons->Open(); - cons->Print("This is debugger console\n"); + // 何か起きるまで待つ + uint32 req; + { + std::unique_lock lock(mtx); + cv_request.wait(lock, [&] { return request != 0; }); + req = request; + request = 0; + } - // 接続ごとに初期化する値 - // XXX もうちょっときれいにしたい - d_last_addr = 0xffffffff; - m_last_addr = 0xffffffff; - n_enable = false; - s_enable = false; - t_enable = false; - is_continued = true; - - // コンソールが繋がっている間がトレースオン - // コンソールが繋がるとプロンプトになる - cpu->atomic_reqflag |= CPU_REQ_TRACE | CPU_REQ_PROMPT; - while (MainLoop() == true) - ; - // コンソールを抜ける時はCPUの停止を解除。 - cpu->atomic_reqflag &= ~CPU_REQ_TRACE; - gCVPrompt->NotifyRelease(); + if ((req & REQUEST_EXIT)) { + break; + } - cons->Close(); + if ((req & REQUEST_RXCHAR)) { + // コンソールからの文字入力 + int c; + while ((c = hostcom->Rx()) >= 0) { + Input(c); + } + } + + if ((req & REQUEST_ACCEPT)) { + // TCP 待ち受けに着信があればすぐにプロンプトを出したい + Input('\n'); + } + + if ((req & REQUEST_PROMPT)) { + // VM 停止(したのでプロンプトモードへ) + EnterPrompt(); + } } - delete cons; + LeavePrompt(); + Close(); } -// プロンプト処理のメイン部分。 -// false を返すとコンソールをクローズする。 -bool -Debugger::MainLoop() +// コンソールをクローズする +void +Debugger::Close() { - // プロンプトが取れるのを待つ - gCVPrompt->WaitAcquire(cons); - - // VM 実行からプロンプトに来たとき - if (is_continued) { - is_continued = false; - - pc = RegPC; - d_last_addr = pc; - // プロンプトに来た時に表示するいつものやつ - cmd_minus(); + if (cons) { + fclose(cons); + cons = NULL; } +} - cons->Print("> "); - cons->Flush(); - if (cons->Gets(cmdbuf, sizeof(cmdbuf)) < 1) { - return false; +#if 0 + bool first = true; + for (;;) { + // 接続後の1回目だけ実行するもの。 + if (first) { + first = false; + + // greeting はプロンプトが取れる前にもう表示したい。 + // 何らかの事故でプロンプトが取れなくても、ここまでは接続 + // できてることが分かるように。 + fprintf(cons, "This is debugger console\n"); + + // 接続ごとに初期化する値 + n_enable = false; + s_enable = false; + t_enable = true; + } + } } - // chomp - for (int i = 0; cmdbuf[i] != '\0'; i++) { - if (cmdbuf[i] == '\r' || cmdbuf[i] == '\n') { - cmdbuf[i] = '\0'; +#endif + +// スレッドに終了指示 +void +Debugger::Terminate() +{ + std::unique_lock lock(mtx); + request |= REQUEST_EXIT; + cv_request.notify_one(); +} + +// funopen の read コールバック +static int +readfunc(void *cookie, char *buf, int bufsize) +{ + return ((Debugger *)cookie)->ReadFunc(buf, bufsize); +} + +// funopen の write コールバック +static int +writefunc(void *cookie, const char *buf, int len) +{ + return ((Debugger *)cookie)->WriteFunc(buf, len); +} + +// funopen の read コールバックの本体 +int +Debugger::ReadFunc(char *buf, int bufsize) +{ + char *d = buf; + char *end = buf + bufsize; + + for (; d < end; ) { + if ((bool)hostcom == false) { + errno = EIO; + return -1; + } + + int c = hostcom->Rx(); + if (c < 0) { break; } + *d++ = c; + } + return (d - buf); +} + +// funopen の write コールバックの本体 +int +Debugger::WriteFunc(const char *buf, int len) +{ + const char *s = buf; + const char *end = buf + len; + + for (; s < end; ) { + if ((bool)hostcom == false) { + errno = EIO; + return -1; + } + + // ホストスレッドのキューが満杯なら空くまで待つ。うーん…。 + // XXX 無期限で大丈夫だろうか + int c = *s++; + if (c == '\n') { + // ここで LF を CRLF にする? + // (TELNET に出力するのに必要) + while (hostcom->Tx('\r') == false) { + usleep(10); + } + } + while (hostcom->Tx(c) == false) { + usleep(10); + } + } + return (s - buf); +} + +// ホストからの1文字受信通知 (HostCOM スレッドから呼ばれる) +void +Debugger::RxCallback() +{ + // デバッガスレッドに通知 + std::unique_lock lock(mtx); + request |= REQUEST_RXCHAR; + cv_request.notify_one(); +} + +// ホストからの着信通知 (HostCOM スレッドから呼ばれる) +void +Debugger::AcceptCallback() +{ + // デバッガスレッドに通知 + std::unique_lock lock(mtx); + request |= REQUEST_ACCEPT; + cv_request.notify_one(); +} + +// ホストからの1文字入力 +void +Debugger::Input(int c) +{ + // '^@' は捨てる + // (意図的にも入力できるが nc が TELNET オプション扱えなくて送ってくる) + if (c == '\0') { + return; + } + + // HostCOM からは改行で CR が来るようなので LF にしておく + if (c == '\r') { + c = '\n'; } - if (cmdbuf[0] != '\0') { - // コマンドが入力されれば次回のために保存 - strcpy(last_cmdbuf, cmdbuf); + if (is_prompt == false) { + // プロンプトでない時は、Enter か ^C でプロンプトを出す + if (c == '\n' || c == '\x03') { + // MPU に一時停止を要求 + is_pause = true; + gScheduler->SendMessage(MessageID::MPU_TRACE, true); + } } else { - // 空行が入力されれば直前のコマンドをもう一度 - // 前行がなければ何もせずもう一度プロンプトを表示するかね - if (last_cmdbuf[0] == '\0') - return true; - strcpy(cmdbuf, last_cmdbuf); + // プロンプト中なら行入力 + + // 先に自力エコーバック?? + fputc(c, cons); + fflush(cons); + + if (c != '\n') { + cmdbuf.push_back(c); + } else { + // Enter ならここでコマンド実行 + + auto act = Command(); + + // 次回との差分のため、今のレジスタセットをバックアップ + md->BackupRegs(); + + switch (act) { + case CmdAct::Stay: + // プロンプトに留まるならここで、次行のプロンプト? + PrintPrompt(); + break; + case CmdAct::Leave: + // プロンプトを抜ける + LeavePrompt(); + break; + case CmdAct::Quit: + // アプリケーション自体を終了 + LeavePrompt(); + UIMessage::Post(UIMessage::APPEXIT); + } + } } +} - // 行を cmd, ac, av に分解 - cmddef_t *cmd = ParseCmd(); - if (cmd == NULL) { - // NULL は知らないコマンドではなく終了コマンド - return false; +// コマンドモード(プロンプト)に入る +void +Debugger::EnterPrompt() +{ + is_prompt = true; + + // d/m をいきなり引数なしで実行した時のため、現在地にしておく。 + pc = md->GetPC(); + m_last_addr.Set(pc, md->IsSuper(), true); + d_last_addr.Set(pc, md->IsSuper(), false); + + // ブレークポイント到達メッセージがあればここで表示 + if (bpointmsg.empty() == false) { + fprintf(cons, "%s", bpointmsg.c_str()); + bpointmsg.clear(); + } + + // プロンプトのたびに表示するやつ + cmd_minus(); + + PrintPrompt(); +} + +// コマンドモード(プロンプト)から出る +void +Debugger::LeavePrompt() +{ + // MPU のトレース状態を変更 + gScheduler->SendMessage(MessageID::MPU_TRACE, IsTrace()); + + is_prompt = false; + + // 最後に VM スレッドで待機している Exec() を起こす + { + std::unique_lock lock(mtx); + prompt_released = true; + cv_prompt.notify_one(); } +} + +// プロンプトを表示 +void +Debugger::PrintPrompt() +{ + fprintf(cons, "> "); + fflush(cons); +} + +// コマンド実行 +Debugger::CmdAct +Debugger::Command() +{ + string_rtrim(cmdbuf); + + if (cmdbuf.empty()) { + // 空行なら、直前のコマンドをもう一度。 + // 前行がなければ何もせずもう一度プロンプトを表示するかね。 + if (last_cmdbuf.empty()) { + return CmdAct::Stay; + } + cmdbuf = last_cmdbuf; + } else { + // 入力された行を次回のために保存 + last_cmdbuf = cmdbuf; + } + + // 行を args に分解 + ParseCmdbuf(); + cmdbuf.clear(); // 前回の値が有効なのはコマンドが連続した時だけ - // コマンド実行 - (this->*(cmd->func))(); - return true; + // コマンドをテーブルから探す + auto it = std::find_if(cmdtable.begin(), cmdtable.end(), + [=](auto x) { return strcmp(args[0].c_str(), x.name) == 0; }); + if (it != cmdtable.end()) { + auto cmd = *it; + + // 見付かれば実行 + return (this->*(cmd.func))(); + } + + // (コマンドテーブルになくて) "r" から始まっていればレジスタ表示系 + if (args[0][0] == 'r') { + // ShowRegister() は処理したら true を返す。 + // "r" 系コマンドはすべて Stay。 + if (md->ShowRegister(cons, args)) { + return CmdAct::Stay; + } + } + + // 知らないコマンドも Stay 相当。 + fprintf(cons, "%s: unknown command\n", args[0].c_str()); + // この行は次回空エンターで再発行しないでいい。 + last_cmdbuf.clear(); + return CmdAct::Stay; +} + +// ブレークポイントとかを調べる。1命令ごとに呼び出される。 +// (VM スレッドから呼ばれる) +void +Debugger::Exec() +{ + if (Check()) { + // 実時間を停止 + gSync->StopRealTime(); + + // 待機 + { + std::unique_lock lock(mtx); + + // notify 前にクリア + prompt_released = false; + + // MPU が一時停止したことをデバッガスレッドへ通知する + request |= REQUEST_PROMPT; + cv_request.notify_one(); + + // デバッガスレッドがプロンプト解放するまで待機 + cv_prompt.wait(lock, [&] { return prompt_released; }); + } + + // 実時間を再開 + gSync->StartRealTime(); + } else { + // t (トレース表示) が有効な場合は終了条件にマッチしなかったここで + // レジスタを表示。終了条件にマッチした時は EnterPrompt() で表示する。 + if (t_enable) { + pc = md->GetPC(); + cmd_minus(); + // 次回との差分のため今のレジスタセットをバックアップ + md->BackupRegs(); + } + } } -// ブレークポイントとかを調べる。 -// CPU_REQ_TRACE フラグが立っている間1命令ごとに呼び出される。 +// MPU をトレース状態にすべきなら true を返す。 bool -debugger_check() +Debugger::IsTrace() const { - return gDebugger->Check(); + // 有効なブレークポイントがあれば MPU をトレースにする + for (const auto& bp : bpoint) { + if (bp.type != BreakpointType::Unused) { + return true; + } + } + + // この辺のどれかがあれば MPU をトレースにする + return bc_enable || ct_enable || s_enable || so_enable || n_enable || + is_pause; } -// デバッガ実行中なら命令開始前にメインルーチンから呼ばれる。 +// デバッガ実行中なら命令開始前に VM スレッドから呼ばれる。 // プロンプトに降りるなら true を返す。 bool Debugger::Check() { - if (t_enable) { - t_count--; - if (t_count == 0) { - t_enable = false; - return true; + bool is_break = false; + + // ブレークポイントは他のチェックとは併用になるので先に調べる。 + if (CheckAllBreakpoints()) { + is_break = true; + } + // アドレス指定付き continue もブレークポイントと似た動作なのでこっち。 + // XXX ブレークポイントとして実装するかどうか + if (bc_enable) { + if (bc_addr == md->GetPC()) { + bc_enable = false; + is_break = true; + } + } + if (ct_enable) { + if (gScheduler->GetVirtTime() >= ct_end_time) { + ct_enable = false; + is_break = true; + + // ブレークポイントメッセージに便乗して表示。 + bpointmsg += string_format("%s has passed.\n", + TimeToStr(ct_timespan).c_str()); } } - if (s_enable) { + // XXX 残りは排他動作のはず + + // いずれの場合も、ステップ実行が終了条件にマッチしたら、ブレークポイント + // の成否に関わらず true を返せばいい。 + // 終了条件が来ないうちに先にブレークポイントに到達した場合でも、ブレーク + // ポイントによりプロンプトに降りるわけなので、実行中のステップ実行を + // キャンセルする。この場合もブレークポイント側が true なので true を + // 返せばよい。 + + // トレース表示に関しては Exec 側でやってある。 + + if (s_enable) { // ステップ実行が成立するか s_count--; - if (s_count == 0) { + if (s_count == 0 || is_break) { s_enable = false; - return true; + t_enable = false; + is_break = true; + } + + } else if (so_enable) { // ステップアウトが成立するか + if (md->IsStepOut() || is_break) { + so_enable = false; + t_enable = false; + is_break = true; + } + + } else if (n_enable) { // 指定命令数実行が完了するか + if (n_breakaddr != 0xffffffff) { + // ステップインをスキップ中 + if (n_breakaddr == md->GetPC()) { + n_count--; + } + } else { + // 1命令実行 + n_count--; + } + if (n_count == 0 || is_break) { + n_enable = false; + t_enable = false; + is_break = true; + } else { + // スキップ中でなければ、ステップインが起きるか都度調べる。 + // すでにスキップ中なら到達するまでは何もしない。 + if (n_breakaddr == 0xffffffff) { + SetNBreakpoint(); + } } } - // n による1命令実行のブレークポイントか - if (n_enable && n_breakenable && n_breakaddr == RegPC) { - n_breakenable = false; - return true; + // デバッガから MPU の一時停止が要求されているか + if (is_pause) { + is_pause = false; + is_break = true; } - // アドレス - for (int i = 0; i < countof(bpoint); i++) { - breakpoint_t *bp = &bpoint[i]; - if (bp->enable) { - if (bp->addr == RegPC) { - bp->count++; - return true; + return is_break; +} + +// ブレークポイントがどれかでも成立するかを調べる。 +// 1つ以上成立してブレークするなら true を返す。 +// 1つも成立しておらずブレークしないなら false を返す。 +// このルーチンから cons への出力は使わないこと。(プロンプトにいない時でも +// 呼ばれるので) +bool +Debugger::CheckAllBreakpoints() +{ + bool is_break = false; + + // 命令ごとにクリアする + bi_inst = 0; + bi_inst_bytes = 0; + + // 1つの条件でマッチしても(そこでブレークすること自体は確定するのだが) + // 残りの他の条件も成立すればカウントを進める必要があるため、 + // 全部処理した上でどれか一つでもブレークしたかで判断する必要がある。 + for (int i = 0, end = bpoint.size(); i < end; i++) { + auto& bp = bpoint[i]; + + switch (bp.type) { + case BreakpointType::Address: + if (bp.addr != md->GetPC()) { + continue; + } + break; + + case BreakpointType::Memory: + if (!md->CheckLEA(bp.addr)) { + continue; + } + break; + + case BreakpointType::Exception: + if (bv_vector >= 0) { + if (bp.vec1 <= bv_vector && bv_vector <= bp.vec2) { + break; + } + } + continue; + + case BreakpointType::Instruction: + if (CheckBreakpointInst(bp) == false) { + continue; } + break; + + default: + continue; } - } - // ステップアウト - if (so_enable) { - if (RegA(7) > so_a7 || (RegSR & 0x3000) != so_sr) { - so_enable = false; - return true; + // 条件は成立したのでカウントとスキップ + bp.matched++; + + // skip == -1 は常にブレークしない (カウントするだけ) + if (bp.skip < 0) { + continue; + } + + // skip が 1 以上なら、remain を減算 + if (bp.skip > 0 && --bp.skipremain > 0) { + continue; + } + + // ブレーク成立 + is_break = true; + + std::string desc; + switch (bp.type) { + case BreakpointType::Address: + desc = string_format("addr $%08x", bp.addr); + break; + case BreakpointType::Memory: + desc = string_format("mem $%08x", bp.addr); + break; + case BreakpointType::Exception: + { + desc = string_format("excp $%02x", bv_vector); + const char *name = gVectorTable->GetExceptionName(bv_vector); + if (name) { + desc += string_format(" \"%s\"", name); + } + break; + } + case BreakpointType::Instruction: + desc = string_format("inst %0*x", + bi_inst_bytes * 2, + bi_inst >> ((4 - bi_inst_bytes) * 8)); + break; + default: + assert(false); + break; } + + // 到達メッセージを作成。 + // この時点ではまだコンソールを取得していない可能性があるので + // (-D なしで起動した場合とか)、表示せず用意するだけ。 + // コンソールが取得できたところで表示する。 + bpointmsg += string_format("breakpoint #%d (%s) reached\n", + i, desc.c_str()); } - // アドレス指定付き continue - if (bc_enable) { - if (bc_addr == RegPC) { - bc_enable = false; - return true; + // 例外通知は通過ごとに常に下ろしておく + bv_vector = -1; + + // ブレークポイントが1つでも成立したかどうかを返す + return is_break; +} + +// 命令ブレークポイントが成立するか調べる。 +bool +Debugger::CheckBreakpointInst(breakpoint_t& bp) +{ + // uint32 bi_inst が現在の PC 位置の命令データ (左詰め) + // bi_inst_bytes が読み込んだバイト数(bi_inst の左からの有効バイト数)。 + // bi_need_bytes が現在のブレークポイントで読み込む必要のあるバイト数。 + + saddr_t laddr(md->GetPC(), md->IsSuper()); + DebuggerMemoryStream mem(md.get(), laddr); + + // 必要なバイト数に達するまで読み足す + bi_inst = 0; + while (bi_inst_bytes < bi_need_bytes) { + uint64 data = mem.FetchInst(); + if ((int64)data < 0) { + return false; } + + bi_inst <<= md->inst_bytes * 8; + bi_inst |= data; + bi_inst_bytes += md->inst_bytes; } + // 左詰めにする + bi_inst <<= (4 - bi_inst_bytes) * 8; + + // 必要なバイト数取得できたので比較 + if ((bi_inst & bp.mask) == bp.inst) { + return true; + } return false; } +// 例外通知 (MPU からの連絡用) +void +debugger_notify_exception(int vector) +{ + gDebugger->NotifyException(vector); +} + +// 例外通知 (本体) +void +Debugger::NotifyException(int vector) +{ + bv_vector = vector; +} + // コマンド一覧。 -// quit コマンドは ParseCmd() 側で処理してある。 -Debugger::cmddef_t Debugger::cmdtable[] = { - { "bx", &Debugger::cmd_bx, }, - { "b", &Debugger::cmd_b, }, - { "brhist", &Debugger::cmd_brhist }, - { "c", &Debugger::cmd_c, }, - { "d", &Debugger::cmd_d, }, - { "dt", &Debugger::cmd_dt, }, - { "D", &Debugger::cmd_D, }, - { "h", &Debugger::cmd_h, }, - { "L", &Debugger::cmd_L, }, - { "m", &Debugger::cmd_m, }, - { "mt", &Debugger::cmd_mt, }, - { "M", &Debugger::cmd_M, }, - { "n", &Debugger::cmd_n, }, - { "r", &Debugger::cmd_r, }, - { "ra", &Debugger::cmd_ra, }, - { "rf", &Debugger::cmd_rf, }, - { "rm", &Debugger::cmd_rm, }, - { "ro", &Debugger::cmd_ro, }, - { "s", &Debugger::cmd_s, }, - { "so", &Debugger::cmd_so, }, - { "show", &Debugger::cmd_show, }, - { "t", &Debugger::cmd_t, }, - { "-", &Debugger::cmd_minus }, -}; -Debugger::cmddef_t Debugger::cmdtable_unknown = { - .name = "", - .func = &Debugger::cmd_unknown, +// "r" から始まるレジスタ表示系コマンドはコード中で別処理してある。 +/*static*/ std::vector Debugger::cmdtable = { + { "bi", &Debugger::cmd_bi, }, + { "bm", &Debugger::cmd_bm, }, + { "bv", &Debugger::cmd_bv, }, + { "bx", &Debugger::cmd_bx, }, + { "b", &Debugger::cmd_b, }, + { "brhist", &Debugger::cmd_brhist, }, + { "c", &Debugger::cmd_c, }, + { "ct", &Debugger::cmd_ct, }, + { "d", &Debugger::cmd_d, }, + { "dt", &Debugger::cmd_dt, }, + { "D", &Debugger::cmd_D, }, + { "disp", &Debugger::cmd_disp, }, + { "exhist", &Debugger::cmd_exhist, }, + { "hb", &Debugger::cmd_hb, }, + { "hr", &Debugger::cmd_hr, }, + { "h", &Debugger::cmd_h, }, + { "help", &Debugger::cmd_h, }, + { "L", &Debugger::cmd_L, }, + { "m", &Debugger::cmd_m, }, + { "mt", &Debugger::cmd_mt, }, + { "M", &Debugger::cmd_M, }, + { "n", &Debugger::cmd_n, }, + { "nt", &Debugger::cmd_nt, }, + { "q", &Debugger::cmd_q, }, + { "quit", &Debugger::cmd_q, }, + { "reset", &Debugger::cmd_reset, }, + { "s", &Debugger::cmd_s, }, + { "st", &Debugger::cmd_st, }, + { "so", &Debugger::cmd_so, }, + { "sot", &Debugger::cmd_sot, }, + { "show", &Debugger::cmd_show, }, + { "t", &Debugger::cmd_t, }, + { "-", &Debugger::cmd_minus, }, }; // ヘルプ -void +// h : 一覧を表示 +// h : 単独コマンドの詳細を表示 +Debugger::CmdAct Debugger::cmd_h() { - if (ac == 1) { - // 引数なし - HelpMain(); - return; - } else { - // 引数あり(今の所対応していない) - HelpMain(); - return; - } + if (args.size() < 2) { + // 引数なしなら一覧表示。 + ShowHelpList(HelpListMain); + return CmdAct::Stay; + } + + // 引数があれば個別の詳細 + bool try_again = false; + std::string cmd = args[1]; + do { + // レジスタ系のヘルプを MD から取得して、ローカル変数で足す + auto details = HelpDetails; + for (const auto& dict : md->GetHelpReg()) { + details.push_back(dict); + } + + // そこから検索 + for (const auto& dict : details) { + if (cmd == dict.first) { + const auto& desc = dict.second; + if (desc[0] == '=') { + // "=" 形式なら を探しなおす。 + // 別名で同じヘルプを指すシンボリックリンクみたいなもの。 + cmd = desc.substr(1); + try_again = true; + break; + } + // そうでなければこれを表示して終了 + std::string disp = HelpConvert(dict.second); + fprintf(cons, "%s", disp.c_str()); + return CmdAct::Stay; + } + } + } while (try_again); + fprintf(cons, "invalid command name: %s\n", args[1].c_str()); + return CmdAct::Stay; } -void -Debugger::HelpMain() +// hb : ブレークポイント系コマンドの一覧を表示 +// こいつだけ結構占めるので別階層。 +Debugger::CmdAct +Debugger::cmd_hb() { - cons->Print(" b ブレークポイント一覧表示\n"); - cons->Print(" b #n ブレークポイント n を削除\n"); - cons->Print(" b $ メモリブレークポイント設定\n"); - cons->Print(" b ブレークポイント設定\n"); - cons->Print(" bx ブレークポイント全削除\n"); - cons->Print(" brhist ブランチ履歴表示\n"); - cons->Print(" c [] 実行再開(continue)\n"); - cons->Print(" d [ [] 逆アセンブル(論理、テーブルサーチなし)\n"); - cons->Print(" dt [ [] 逆アセンブル(論理、テーブルサーチあり)\n"); - cons->Print(" D [ [] 逆アセンブル(物理)\n"); - cons->Print(" h ヘルプ(help)\n"); - cons->Print(" L = ログレベル設定\n"); - cons->Print(" m [ [] メモリダンプ(論理、テーブルサーチなし)\n"); - cons->Print(" mt [ [] メモリダンプ(論理、テーブルサーチあり)\n"); - cons->Print(" M [ [] メモリダンプ(物理)\n"); - cons->Print(" n ステップ実行 (サブルーチンを飛ばす)\n"); - cons->Print(" q quit\n"); - cons->Print(" r [a|f|m|o] レジスタ表示\n"); - cons->Print(" so ステップアウト\n"); - cons->Print(" show モニター表示\n"); - cons->Print(" t トレース実行\n"); + return ShowHelpList(HelpListBreakpoints); } -// 知らないコマンドを処理するというコマンド -void -Debugger::cmd_unknown() +// hr : レジスタ表示系コマンドの一覧を表示 +// CPU ごとに違うので。 +Debugger::CmdAct +Debugger::cmd_hr() { - cons->Print("%s: unknown command\n", av[0]); + return ShowHelpList(md->GetHelpListReg()); } -// cmdbuf を cmd, ac, av に分解する。 -// cmdbuf は破壊されるので以後は cmd, ac, av で参照のこと。 -// コマンド(の1ワード目)が一致しなければ cmd_unknown を返し、 -// 終了コマンドと一致したら NULL を返す。 -Debugger::cmddef_t * -Debugger::ParseCmd() +// ヘルプ一覧を表示。 +Debugger::CmdAct +Debugger::ShowHelpList(const HelpMessages& msgs) { - char *p; - cmddef_t *cmd; + fprintf(cons, "Type \"help \" for indivisual details.\n"); + for (const auto& pair : msgs) { + fprintf(cons, " %-16s %s\n", pair.first.c_str(), pair.second.c_str()); + } + return CmdAct::Stay; +} - p = cmdbuf; - ac = 0; - memset(&av, 0, sizeof(av)); +// 個別ヘルプメッセージを出力用に置換。 +// 1. 行頭の連続する改行 (通常は1つのはず) を取り除く。 +// 2. 末尾の連続するタブ (通常は1つのはず) を取り除く。 +// 3. (各行頭の) タブを空白4つに置換する。 +std::string +Debugger::HelpConvert(const std::string& src) +{ + int start = 0; + int len = src.size(); - // 引数を空白で分解 - for (; ac < countof(av); ) { - // 先頭の空白は取り除く - while (isspace((int)*p)) - p++; - if (*p == '\0') - break; + // 末尾の連続するタブをカウント + while (src[len - 1] == '\t') { + len--; + } + // 先頭の連続する改行をカウント + while (src[start] == '\n') { + start++; + len--; + } + std::string stripped = src.substr(start, len); - av[ac++] = p; - // 次の空白まで進める - for (; *p != '\0'; p++) { - if (isspace((int)*p)) - break; + // 面倒なので行頭に関わらず全タブを置換 + const char *c_stripped = stripped.c_str(); + std::string dst; + for (const char *s = c_stripped; *s; s++) { + if (*s == '\t') { + dst.append(" "); + } else { + dst.append(1, *s); } - if (*p != '\0') - *p++ = '\0'; } + return dst; +} + +/*static*/ const HelpMessages +Debugger::HelpListMain = { + { "b*", "Set/show Breakpoints (Type \"hb\" for details)" }, + { "brhist", "Show branch history" }, + { "c/ct", "Continue" }, + { "d/dt/D", "Disassemble" }, + { "disp", "Set register group to show" }, + { "exhist", "Show exception history" }, + { "help", "Show this message" }, + { "L", "Set log level" }, + { "m/mt/M", "Memory dump" }, + { "n/nt", "Step until next instruction (Skip subroutines)" }, + { "quit", "Quit" }, + { "r*", "Show registers (Type \"hr\" for details)" }, + { "reset", "Reset the VM" }, + { "s/st", "Step an instruction (Step in)" }, + { "so", "Step out" }, + { "show", "Show monitor" }, +}; - // コマンドを探す - for (int i = 0; i < countof(cmdtable); i++) { - cmd = &cmdtable[i]; +/*static*/ const HelpMessages +Debugger::HelpListBreakpoints = { + { "b", "Show all breakpoints" }, + { "b arg..","Set/Delete breakpoint" }, + { "bm", "Set memory breakpoint" }, + { "bi", "Set instruction breakpoint" }, + { "bv", "Set exception breakpoint" }, + { "bx", "Delete all breakpoints" }, +}; - // デバッガから抜ける(終了する)コマンドだけここで処理 - if (strcmp(av[0], "q") == 0 || strcmp(av[0], "quit") == 0) - return NULL; +// 各コマンドの詳細。"コマンド名" => "説明文" の形式。 +// 説明文は C+11 の生文字リテラル機能を使って R"**( )**" で囲む。 +// 1つのエントリは +// { "cmdname", R"**( +// cmdname [argument...] +// +// Description... +// )**" }, +// のようになる。説明文本文はインデント1つ(TAB 幅 4) で字下げした状態で +// 80桁以内に収めること。出力の際にタブを空白4つに置き換えることでソース上 +// での見た目と実際の出力とを揃えてある。 +// またソースコード上の見栄えの問題として、文字列の開始記号、終了記号を本文 +// とは別の行に書いているため、オブジェクトとしての文字列には先頭に改行、 +// 末尾にタブが余計に入っているが、これは表示の際にコードで取り除く。 +// +// 説明文の書き方は、まずコマンド書式を1行ずつ書く。 +// コマンド書式と本文との間は1行あける。 +/*static*/ const HelpMessages +Debugger::HelpDetails = { + //----- + { "b", R"**( + Command: b + Command: b
[] + Command: b #n + + The first form (with no arguments) shows all breakpoints. + The second form sets a new breakpoint on
. + XXX skipcount + If is -1, it will never match. It's useful to count the + number of times you have passed this address. + The third form deletes a breakpoint specified by number. + )**" }, + + //----- + { "bm", R"**( + Command: bm
[] + + Sets a memory breakpoint on
. + XXX skipcount + If is -1, it will never match. It's useful to count the + number of times you have passed this address. + )**" }, + + //----- + { "bi", R"**( + Command: bi [:] [] + + Sets an instruction breakpoint. must be 16 bits or 32 bits on + m68k and must be 32 bits on m88k. can specify the mask. Its + length must be the same as . If the is ommited, all bits + of is used to compare. + For example, + "bi 4e75" on m68k will stop at 'rts' instruction. + "bi 70004e4f:fff0ffff" on m68k will stop at any of 'IOCS #0'..'IOCS #15'. + + XXX skipcount + If is -1, it will never match. It's useful to count the + number of times you have passed this address. + )**" }, + + //----- + { "bv", R"**( + Command: bv [-] [] + + Sets an exception breakpoint. must be specified in hex. + ranges from 0 to ff (255 in decimal) on m68k, and 0 to 1ff (511 + in decimal) on m88k. If is specified, it matches the range + from to (including themselves). + For example, "bv 1-1ff" on m88k means all exceptions but reset. + XXX skipcount + If is -1, it will never match. It's useful to count the + number of times you have passed this address. + )**" }, + + //----- + { "bx", R"**( + Command: bx + + Deletes all breakpoints. + )**" }, + + //----- + { "brhist", R"**( + Command: brhist [] + + Show branch history. specifies the maximum number of lines + to display. If is negative value, sort in reverse order. + )**" }, + + //----- + { "c", R"**( + Command: c [
] + + Continue (until
if specified). + )**" }, + + //----- + { "ct", R"**( + Command: ct [] + + Continue until specified has elapsed. If the is + ommited, the last value is used again. The unit of is + seconds in default. You can use "msec", "usec", or "nsec" suffix. + )**" }, + + //----- + { "d", R"**( + Command: D
] [] + Command: d [[:]
] [] + Command: dt [[:]
] [] + + Shows disassemble. + The first form ("D") interprets
as a physical address. + The second and third form ("d", "dt") interprets
as a logical + address if the address translation is enabled. Normally,
is + interpreted in the current privilege and current address space. You can + change it by modifier. + On m68k, can be specified either by function code number directly + ('1', '2', '5', and '6) or by one or more following modifiers: + 's' .. Supervisor mode 'u' .. User mode + 'd' .. Data space 'p' or 'i' .. Program space + On m88k, can be specified by using combination of privilege + modifier ('s' or 'u', same as above) and following CMMU identifiers: + 'd' .. Data CMMU 'i' or 'p' .. Instruction CMMU + Or CMMU can also be identified by CMMU number (like '6' or '7'). + + "d" only looks up in ATC (on m68k) or in BATC/PATC (on m88k). + "dt" will simulate to search the page table in addition to that. + )**" }, + { "dt", "=d" }, + { "D", "=d" }, + + //----- + { "disp", R"**( + Command: disp + + Sets the registers list to be shown in the trace. + is comma-separated list and each of which is a command + name that shows registers. See "hr". + The default is "r" and thus it only shows general registers in the trace. + For example, if you set "disp r,rf", it will show general registers and + FPU registers in every trace. + )**" }, + + //----- + { "exhist", R"**( + Command: exhist [] + + Show exception history. specifies the maximum number of lines + to display. If is negative value, sort in reverse order. + )**" }, + + //----- + { "help", R"**( + Command: help [] + Command: hb + Command: hr + + The "help" command without arguments shows the list of commands. + The "help" command with an argument shows 's detailed help. + "h" is a synonym of "help". + The "hb" command shows the list of breakpoint-related commands. + The "hr" command shows the list of register-related commands. + )**" }, + { "h", "=help" }, + { "hb", "=help" }, + { "hr", "=help" }, + + //----- + { "L", R"**( + Command: L [=][,=[]]... + + Set loglevel. XXX To be written... + )**" }, + + //----- + { "m", R"**( + Command: M
] [] + Command: m [[:]
] [] + Command: mt [[:]
] [] + + Shows memory dump. + The first form ("M") interprets
as a physical address. + The second and third form ("m", "mt") interprets
as a logical + address if the address translation is enabled. Normally,
is + interpreted in the current privilege and current address space. You can + change it by modifier. + On m68k, can be specified either by function code number directly + ('1', '2', '5', and '6) or by one or more following modifiers: + 's' .. Supervisor mode 'u' .. User mode + 'd' .. Data space 'p' or 'i' .. Program space + On m88k, can be specified by using combination of privilege + modifier ('s' or 'u', same as above) and following CMMU identifiers: + 'd' .. Data CMMU 'i' or 'p' .. Instruction CMMU + Or CMMU can also be identified by CMMU number (like '6' or '7'). + + "m" only looks up in ATC (on m68k) or in BATC/PATC (on m88k). + "mt" will simulate to search the page table in addition to that. + )**" }, + { "mt", "=m" }, + { "M", "=m" }, + + //----- + { "n", R"**( + Command: n [] + Command: nt [] + + Step one (or ) instructions. Unlike "s" command, "n" skips + subroutine. + If "t" is suffixed, it shows a trace for each instruction (including + while skipping). + )**" }, + { "nt", "=n" }, + + //----- + { "quit", R"**( + Command: quit (or q) + + Quit the debugger console. This continues the execution, as same as "c". + )**" }, + { "q", "=quit" }, + + //----- + { "reset", R"**( + Command: reset + + Reset the VM. Currently this does the hardware reset. + )**" }, + + //----- + { "s", R"**( + Command: s [] + Command: st [] + + Step one (or ) instructions. Unlike "n" command, "s" steps in + subroutine. + If "t" is suffixed, it shows a trace for each instruction. + + "t" command is a synonym of "st" for backward compatibility. + )**" }, + { "st", "=s" }, + + //----- + { "so", R"**( + Command: so + Command: sot + + Step out this sub routine. + If "t" is suffixed, it shows a trace for each instruction. + )**" }, + + //----- + { "show", R"**( + Command: show - if (strcmp(av[0], cmd->name) == 0) - return cmd; - } + Shows the specified monitor. + )**" }, - // 見つからなければ cmd_unknown コマンドを実行。 - return &cmdtable_unknown; + //----- + { "t", "=s" }, +}; + +// cmdbuf を args... に分解する。 +void +Debugger::ParseCmdbuf() +{ + int pos; + int start; + + pos = 0; + args.clear(); + + // 引数を空白で分解 + for (;;) { + // 先頭の空白はスキップ + for (; cmdbuf[pos] != '\0'; pos++) { + if (!isspace((unsigned int)cmdbuf[pos])) + break; + } + if (cmdbuf[pos] == '\0') + break; + + // 終わりを探す + start = pos; + for (; cmdbuf[pos] != '\0'; pos++) { + if (isspace((unsigned int)cmdbuf[pos])) + break; + } + args.push_back(cmdbuf.substr(start, pos - start)); + } + // デバッグ表示 + if (0) { + for (int i = 0 ; i < args.size(); i++) { + printf("args[%d]=|%s|\n", i, args[i].c_str()); + } + } } // @@ -481,344 +1290,1017 @@ Debugger::ParseCmd() // // ブレークポイント -void +// b ... 一覧表示 +// b #n ... #n を削除 +// b [] ... 設定 +Debugger::CmdAct Debugger::cmd_b() { // 引数なしなら一覧表示 - if (ac < 2) { + if (args.size() < 2) { return cmd_b_list(); } // 引数取得 - if (av[1][0] == '#') { + if (args[1][0] == '#') { // # 形式なら、指定番号のブレークポイントを削除 - int i = atoi(&av[1][1]); - if (i < 0 || i >= MAX_BREAKPOINTS) { - cons->Print("invaild break point number: #%d\n", i); - return; - } - breakpoint_t *bp = &bpoint[i]; - if (bp->enable) { - cons->Print("%sbreakpoint #%d (%08x) removed\n", - bp->ismemory ? "memory " : "", i, bp->addr); - bp->enable = false; - } else { - cons->Print("breakpoint #%d not enabled\n", i); - } - return; + cmd_b_delete(); + return CmdAct::Stay; } - bool ismemory; - uint32 addr; - if (av[1][0] == '$') { - // $ 形式ならメモリブレークポイント - ismemory = true; - addr = strtoul(&av[1][1], NULL, 16); + return cmd_b_set(BreakpointType::Address); +} + +// メモリブレークポイントの設定 +// bm [] +Debugger::CmdAct +Debugger::cmd_bm() +{ + // XXX m68k では未サポート + if (md->arch == DebuggerMD::Arch::M680x0) { + fprintf(cons, "bm not supported yet on m68k\n"); + return CmdAct::Stay; + } + return cmd_b_set(BreakpointType::Memory); +} + +// type が違うだけの各種ブレークポイント設定の共通部分。 +Debugger::CmdAct +Debugger::cmd_b_set(BreakpointType type) +{ + breakpoint_t bp; + + if (args.size() < 2) { + fprintf(cons, "usage: %s []\n", args[0].c_str()); + return CmdAct::Stay; + } + + // アドレス + if (!ParseAddr(args[1].c_str(), &bp.addr)) { + return CmdAct::Stay; + } + // あればスキップカウント + if (args.size() > 2) { + bp.skip = atoi(args[2].c_str()); + } + + // 空いてるところにセット + // (よく似たエントリがあっても干渉しない) + bp.type = type; + int bi = AddBreakpoint(bp); + if (bi == -1) { + fprintf(cons, "no free breakpoints\n"); + } else { + fprintf(cons, "breakpoint #%d added\n", bi); + } + return CmdAct::Stay; +} + +// ブレークポイント個別削除 +// (引数の先頭が '#' なことを判定したところで呼ばれる) +// b # +Debugger::CmdAct +Debugger::cmd_b_delete() +{ + int n = atoi(&args[1][1]); + if (n < 0 || n >= bpoint.size()) { + fprintf(cons, "invalid breakpoint number: #%d\n", n); + return CmdAct::Stay; + } + + auto& bp = bpoint[n]; + if (bp.type == BreakpointType::Unused) { + fprintf(cons, "invalid breakpoint number: #%d\n", n); + return CmdAct::Stay; + } + + fprintf(cons, "breakpoint #%d removed\n", n); + bp.type = BreakpointType::Unused; + // 今登録されている命令ブレークの必要命令長を再計算 + RecalcInstMask(); + return CmdAct::Stay; +} + +// 命令ブレークポイントの設定 +// bi [:] [] +Debugger::CmdAct +Debugger::cmd_bi() +{ + breakpoint_t bp; + std::string inststr; + std::string maskstr; + int instlen; + int masklen; + + if (args.size() < 2) { + fprintf(cons, "usage: bi [:] []\n"); + return CmdAct::Stay; + } + + // 引数をまず分離 + auto pos = args[1].find(':'); + if (pos == std::string::npos) { + // マスク指定なし + inststr = args[1]; + instlen = inststr.size(); + masklen = -1; } else { - // そうでなければアドレス指定 - ismemory = false; - addr = strtoul(av[1], NULL, 16); + // マスク指定あり + inststr = args[1].substr(0, pos); + instlen = inststr.size(); + maskstr = args[1].substr(pos + 1); + masklen = maskstr.size(); + } + + // 命令部チェック + if (ParseVerbHex(inststr.c_str(), &bp.inst) == false) { + fprintf(cons, "%s: invalid instruction value\n", args[1].c_str()); + return CmdAct::Stay; + } + if (instlen % (md->inst_bytes * 2) != 0) { + fprintf(cons, "%s: invalid instruction length\n", args[1].c_str()); + return CmdAct::Stay; + } + + // マスク部チェック + bp.mask = 0xffffffff; + if (masklen != -1) { + if (ParseVerbHex(maskstr.c_str(), &bp.mask) == false) { + fprintf(cons, "%s: invalid mask value\n", args[1].c_str()); + return CmdAct::Stay; + } + if (masklen != instlen) { + fprintf(cons, "%s: inst:mask must be the same length\n", + args[1].c_str()); + return CmdAct::Stay; + } + } + // 8バイト未満なら左詰め。 + if (md->inst_bytes < 4 && instlen < 8) { + bp.inst <<= 32 - instlen * 4; + bp.mask <<= 32 - instlen * 4; + } + + // あればスキップカウント + bp.skip = 0; + if (args.size() > 2) { + bp.skip = atoi(args[2].c_str()); } - // すでにあればそのブレークポイントを削除 - for (int i = 0; i < MAX_BREAKPOINTS; i++) { - breakpoint_t *bp = &bpoint[i]; - if (bp->enable && bp->ismemory == ismemory && bp->addr == addr) { - bp->enable = false; - cons->Print("%sbreakpoint #%d (%08x) removed\n", - bp->ismemory ? "memory " : "", i, bp->addr); - return; + // 空いてるところにセット + bp.type = BreakpointType::Instruction; + int bi = AddBreakpoint(bp); + if (bi == -1) { + fprintf(cons, "no free breakpoints\n"); + } else { + fprintf(cons, "breakpoint #%d added\n", bi); + } + + // 今登録されている命令ブレークの必要命令長を再計算 + RecalcInstMask(); + return CmdAct::Stay; +} + +// 例外ブレークポイントの設定 +// bv [-] [] +Debugger::CmdAct +Debugger::cmd_bv() +{ + breakpoint_t bp; + + if (args.size() < 2) { + fprintf(cons, "usage: be [-] []\n"); + return CmdAct::Stay; + } + + auto pos = args[1].find('-'); + if (pos == std::string::npos) { + // ベクタ番号が1つなら vec1, vec2 を同値にしておく。 + if (ParseVerbHex(args[1].c_str(), (uint32 *)&bp.vec1) == false) { + fprintf(cons, "%s: invalid vector number\n", args[1].c_str()); + return CmdAct::Stay; + } + bp.vec2 = bp.vec1; + } else { + // ベクタ番号(範囲指定 [vec1, vec2]) + std::string str1 = args[1].substr(0, pos); + std::string str2 = args[1].substr(pos + 1); + + if (ParseVerbHex(str1.c_str(), (uint32 *)&bp.vec1) == false) { + fprintf(cons, "%s: invalid first vector number\n", args[1].c_str()); + return CmdAct::Stay; + } + if (ParseVerbHex(str2.c_str(), (uint32 *)&bp.vec2) == false) { + fprintf(cons, "%s: invalid last vector number\n", args[1].c_str()); + return CmdAct::Stay; } } + // 範囲チェック + if (bp.vec1 < 0 || bp.vec1 >= gVectorTable->Size()) { + fprintf(cons, "$%x: invalid vector number\n", bp.vec1); + return CmdAct::Stay; + } + if (bp.vec2 < 0 || bp.vec2 >= gVectorTable->Size()) { + fprintf(cons, "$%x: invalid last vector number\n", bp.vec2); + return CmdAct::Stay; + } + + // 大小が逆なら入れ替える? + if (bp.vec1 > bp.vec2) { + int tmp; + tmp = bp.vec1; + bp.vec1 = bp.vec2; + bp.vec2 = tmp; + } + + // あればスキップカウント + bp.skip = 0; + if (args.size() > 2) { + bp.skip = atoi(args[2].c_str()); + } + // 空いてるところにセット - int bi = AddBreakpoint(addr, ismemory); + bp.type = BreakpointType::Exception; + int bi = AddBreakpoint(bp); if (bi == -1) { - cons->Print("no free breakpoints!\n"); + fprintf(cons, "no free breakpoints\n"); } else { - breakpoint_t *bp = &bpoint[bi]; - cons->Print("%sbreakpoint #%d (%08x) added\n", - bp->ismemory ? "memory " : "", bi, bp->addr); + fprintf(cons, "breakpoint #%d added\n", bi); } + + // すでに来ている例外をクリア。 + // ブレークポイント設定の有無に関わらず例外が起きたら CPU 側から常に + // 通知されている。これをクリアするのは CheckAllBreakpoints() で、これは + // 命令間(命令前)に呼ばれるやつ、なのでこうなる。 + // 1. 例外が起きると bv_vector がセットされる + // 2. 例外ブレークポイントを設定していないとこれがクリアされない + // 3. bv コマンドで例外ブレークを新たに設定すると、次の命令境界で + // 1.のベクタが反応してしまう。 + // 命令ごととかにクリアしてもいいかも知れないが、ここでブレークポイントを + // 設定したのだから、それ以前の事象には反応すべきでない、という意味では + // ここでもいいか? + bv_vector = -1; + + return CmdAct::Stay; } // ブレークポイント一覧表示 -void +Debugger::CmdAct Debugger::cmd_b_list() { - int found = 0; + ShowMonitor(bpoint_monitor); + return CmdAct::Stay; +} + +// ブレークポイント一覧 (モニタ) +void +Debugger::MonitorUpdateBpoint(Monitor *, TextScreen& monitor) +{ + // 0 1 2 3 4 5 6 + // 0123456789012345678901234567890123456789012345678901234567890 + // No Type Parameter Matched Skip + // #0 addr $01234567 123456789 123456789/123456789 + // #1 inst 00000000/00000000 + // #2 excp $00-$00 + + monitor.Clear(); + monitor.Print(0, 0, "No Type Parameter"); + monitor.Print(26, 0, "Matched"); + monitor.Print(37, 0, "Skip"); + + for (int i = 0; i < bpoint.size(); i++) { + const auto& bp = bpoint[i]; + int y = i + 1; + + monitor.Print(0, y, "#%d", i); + + // 種別ごとの表示 + switch (bp.type) { + case BreakpointType::Unused: + continue; + + case BreakpointType::Address: + monitor.Print(3, y, "addr $%08x", bp.addr); + break; + case BreakpointType::Memory: + monitor.Print(3, y, "mem $%08x", bp.addr); + break; + + case BreakpointType::Exception: + monitor.Print(3, y, "excp $%02x", bp.vec1); + if (bp.vec2 != bp.vec1) { + monitor.Print(11, y, "-$%02x", bp.vec2); + } + break; + + case BreakpointType::Instruction: + monitor.Print(3, y, "inst"); + if (md->inst_bytes == 4) { + if (bp.mask == 0xffffffff) { + monitor.Print(8, y, "%08x", bp.inst); + } else { + monitor.Print(8, y, "%08x:%08x", bp.inst, bp.mask); + } + } else { + if (bp.mask == 0xffffffff) { + monitor.Print(8, y, "%08x", bp.inst); + } else if (((bp.inst | bp.mask) & 0x0000ffff) != 0) { + monitor.Print(8, y, "%08x:%08x", bp.inst, bp.mask); + } else if (bp.mask == 0xffff0000) { + monitor.Print(8, y, "%04x", bp.inst >> 16); + } else { + monitor.Print(8, y, "%04x:%04x", + bp.inst >> 16, bp.mask >> 16); + } + } + break; - for (int i = 0; i < MAX_BREAKPOINTS; i++) { - breakpoint_t *bp = &bpoint[i]; - if (bp->enable) { - cons->Print(" #%d %s%08x %d\n", - i, - bp->ismemory ? "memory $" : "", - bp->addr, bp->count); - found = 1; + default: + monitor.Print(3, y, "type=%d", (int)bp.type); + continue; + } + + // マッチ回数 + monitor.Print(26, y, "%d", bp.matched); + + // スキップ + if (bp.skip < 0) { + monitor.Print(37, y, "forever"); + } else if (bp.skip > 0) { + monitor.Print(37, y, "%d / %d", (bp.skip - bp.skipremain), bp.skip); } - } - if (found == 0) { - cons->Print(" No breakpoints enabled\n"); } } // ブレークポイント全削除 -void +Debugger::CmdAct Debugger::cmd_bx() { - for (int i = 0; i < MAX_BREAKPOINTS; i++) { - breakpoint_t *bp = &bpoint[i]; - bp->enable = false; + for (auto& bp : bpoint) { + bp.type = BreakpointType::Unused; } - cons->Print(" All breakpoints disabled\n"); + fprintf(cons, " All breakpoints disabled\n"); + + // 今登録されている命令ブレークの必要命令長を再計算 + RecalcInstMask(); + + return CmdAct::Stay; } // ブレークポイントを設定。 -// 設定できればその番号、できなければ -1 を返す -// TODO 重複の処理とか +// new_bp のうち matched, skipremain はこちらで初期化する。 +// それ以外を埋めてから呼ぶこと。 +// 設定できればその番号、できなければ -1 を返す。 int -Debugger::AddBreakpoint(uint32 addr, bool ismemory) +Debugger::AddBreakpoint(const breakpoint_t& new_bp) { - for (int i = 0; i < countof(bpoint); i++) { - breakpoint_t *bp = &bpoint[i]; - if (!bp->enable) { - bp->enable = true; - bp->addr = addr; - bp->ismemory = ismemory; - bp->count = 0; + for (int i = 0; i < bpoint.size(); i++) { + auto& bp = bpoint[i]; + if (bp.type == BreakpointType::Unused) { + bp = new_bp; + bp.matched = 0; + if (bp.skip > 0) { + bp.skipremain = bp.skip; + } else { + bp.skipremain = 0; + } + return i; } } return -1; } -// ブランチ履歴表示 +// すべての命令ブレークのマスクのうち最長のものを再計算する。 +// 命令ブレークポイントの追加/削除のたびに呼び出すこと。 void +Debugger::RecalcInstMask() +{ + uint32 mask; + bi_need_bytes = 0; + + // 登録されている命令ブレークの最長マスクを求める + mask = 0; + for (const auto& bp : bpoint) { + if (bp.type == BreakpointType::Instruction) { + mask |= bp.mask; + } + } + + // mask の Number of Trailing Zero を求める。 + // (x & -x) で x の最も下の立ってるビットだけを立てる、 + // (x & -x) -1 でそれより下の全ビットを立てる、 + // それを popcount で数えるので、$fffffff0 なら ntz = 4 になる。 + int ntz = __builtin_popcount((mask & -(int32)mask) - 1); + // 上位側から数えたマスクに必要なビット数 + int mlen = 32 - ntz; + // 命令語単位に切り上げる + mlen = roundup(mlen, md->inst_bytes * 8); + // バイト数に変換 + mlen /= 8; + + if (mlen > bi_need_bytes) { + bi_need_bytes = mlen; + } +} + +// ブランチ履歴、例外履歴表示 +// brhist [] +// exhist [] +// は表示する最大エントリ数。 +// コンソールではデフォルトで下を新しいの順とする。 を負数にすると +// (行数は絶対値して) 並び順を逆にしてモニタウィンドウと同じ上を新しいの順に +// する。 +Debugger::CmdAct Debugger::cmd_brhist() { - gMPUBrHist->MonitorUpdate(); - ShowMonitor(gMPUBrHist->monitor); + return cmd_hist_common(md->GetBrHist()); +} +Debugger::CmdAct +Debugger::cmd_exhist() +{ + return cmd_hist_common(md->GetExHist()); +} + +// ブランチ履歴、例外履歴表示の共通部分。 +Debugger::CmdAct +Debugger::cmd_hist_common(BranchHistory& hist) +{ + // 表示最大行数(と向き) + // 向きは bottom_to_top = true が新しいほうを下とする方向。 + int maxlines = 20; + bool bottom_to_top = true; + if (args.size() > 1) { + maxlines = atoi(args[1].c_str()); + if (maxlines < 0) { + bottom_to_top = false; + maxlines = -maxlines; + } + + if (maxlines < 1) + maxlines = 1; + if (maxlines > 256) + maxlines = 256; + } + + // コンソールでは空エントリの行は表示したくないので、 + // 先にエントリ数を調べる。 + int used = hist.GetUsed(); + + // 表示行数 + 1行はヘッダ分 + int lines = std::min(used, maxlines) + 1; + + // MonitorUpdate() は TextScreen 高さに合わせて出力してくれる。 + auto& histmon = hist.monitor; + auto size = histmon.GetSize(); + TextScreen screen; + screen.Init(size.width, lines); + + // コンソールでは下が新しいの順のほうがいい + if (bottom_to_top) { + screen.userdata |= BranchHistory::BottomToTop; + } + + // 表示 + MONITOR_UPDATE(histmon, screen); + ShowTextScreen(screen); + + return CmdAct::Stay; } // 実行再開(continue): c [] // 指定があれば まで実行。 -void +Debugger::CmdAct Debugger::cmd_c() { - if (ac > 1) { + if (args.size() > 1) { // 引数があれば - if (!ParseAddr(av[1], &bc_addr)) { - return; + if (!ParseAddr(args[1].c_str(), &bc_addr)) { + return CmdAct::Stay; } // 偶数番地に丸める bc_addr &= 0xfffffffe; bc_enable = true; } - Continue(); + return CmdAct::Leave; } -// 実行再開 -void -Debugger::Continue() +// 指定仮想時間実行: ct [