--- nono/lib/mainapp.cpp 2026/04/29 17:04:30 1.1.1.2 +++ nono/lib/mainapp.cpp 2026/04/29 17:05:15 1.1.1.14 @@ -1,17 +1,67 @@ // // nono -// Copyright (C) 2018 isaki@NetBSD.org +// Copyright (C) 2020 nono project +// Licensed under nono-license.txt +// + +// +// CLI/GUI 共通のメイン部分 // -#include "header.h" #include "mainapp.h" +#include "config.h" +#include "hostnet.h" +#include "logger.h" +#include "monitor.h" #include "mystring.h" +#include "mythread.h" +#include "sram.h" +#include "vm_luna.h" +#include "vm_news.h" +#include "vm_x68k.h" +#include #include +#include #include +#include +#if defined(__linux__) +#include +#endif // グローバルインスタンス MainApp gMainApp; +// コンストラクタ +MainApp::MainApp() +{ +} + +// デストラクタ +MainApp::~MainApp() +{ + // 逆順に解放 + + pVM.reset(); + + pConfig.reset(); + gConfig = NULL; + + pMonitorManager.reset(); + gMonitorManager = NULL; + +#if 0 // 確認用 + if (objects.empty() == false) { + printf("~MainApp: undead objects are:"); + for (const auto *obj : objects) { + printf(" %s", obj->GetIdStr()); + } + printf("\n"); + } +#endif + + logger.reset(); +} + // ヘルプメッセージ void MainApp::ShowHelp(bool all) const @@ -21,29 +71,35 @@ MainApp::ShowHelp(bool all) const #define p(msg) printf(" " msg "\n") printf("usage: %s []\n", getprogname()); - p("-A load and execute host binary (a.out or ELF)"); - p("-c vm directory"); - p("-f fast mode"); + p("-c vm directory or configuration file"); + p("-f fast mode (same as '-V fast-mode=1')"); if (IsGUI()) - p("--fontsize fontsize in monitors {12,16,24} (default:12)"); + p("--fontsize fontsize (same as '-V monitor-fontsize=')"); p("-h show brief help message"); p("--help show all help message including for developers"); if (IsGUI()) - p("-s,--scale screen scale, default 1.0"); + p("-s mainview scale (same as '-V mainview-scale=')"); p("--show-config show configuration variables"); + p("--show-hostnet show list of hostnet drivers"); p("-v show version"); p("-V = overwrite config option"); + p("-X [arg..] load and execute host binary (a.out or ELF)"); if (all) { printf("\n(options for developers)\n"); - p("-b breakpoint"); + p("-b [,][,]"); + p(" set breakpoint. is either 'main'(default) or 'xp'"); p("-B benchmark mode"); p("-C output log to console"); p("-d debugger prompt on startup"); - p("-D debugger on console"); + p("-D same as '-V debugger-driver=stdio'"); + p("-H human68k console emulation"); p("-L =[,..] set loglevel (-Lhelp displays names)"); + p("--load-only load host binary (a.out or ELF) but not execute"); p("-M [,..] monitors to display at startup (-Mhelp displays names)"); - p("-X human68k console emulation"); + p(" memdump[=[.]] fmt := B/W/L/M(MMU)/I(Disasm)/Z(XPDisasm)"); + p("-S MSX-DOS console emulation"); + p("--perf performance measure mode"); } } @@ -51,136 +107,217 @@ MainApp::ShowHelp(bool all) const // enum は getopt() の1文字のオプションと衝突しなければいいので適当に // 0x80 から始めておく。 enum { - OPT_fontsize = 0x80, + OPTstart = 0x80 - 1, + OPT_create_sram, + OPT_fontsize, + OPT_load_only, OPT_help, + OPT_perf, OPT_show_config, + OPT_show_config_all, + OPT_show_hostnet, }; static struct option longopts[] = { + { "create-sram", no_argument, NULL, OPT_create_sram }, { "fontsize", required_argument, NULL, OPT_fontsize }, + { "load-only", required_argument, NULL, OPT_load_only }, { "help", no_argument, NULL, OPT_help }, + { "perf", no_argument, NULL, OPT_perf }, { "show-config", no_argument, NULL, OPT_show_config }, + // --show-config-all は開発用なのでヘルプには載せない + { "show-config-all",no_argument, NULL, OPT_show_config_all }, + { "show-hostnet", no_argument, NULL, OPT_show_hostnet }, { NULL, 0, NULL, 0 }, }; -// 起動時の処理、VM の実行開始前まで。 +// VM の初期化、ステージ1。 +// VM 作成と設定確定あたりまで。スレッド生成を伴わないもの。 // 所々 CLI と GUI で処理が違う。 -bool -MainApp::Init(bool is_cli_, int ac, char *av[]) +// 戻り値は以下のいずれか。 +// MainApp::PASS .. 実行を継続(通常パス) +// EXIT_SUCCESS / EXIT_FAILURE .. この終了コードでアプリケーションを終了 +int +MainApp::Init1(bool is_cli_, int ac, char *av[]) { + int rv; + is_cli = is_cli_; - if (!ParseOpt(ac, av)) { - return false; +#if defined(__linux__) + // Linux ではケーパビリティが設定されていると coredump しないので + // 明示的に許可する必要がある + prctl(PR_SET_DUMPABLE, 1, 0, 0, 0); +#endif + + rv = ParseOpt(ac, av); + if (rv != MainApp::PASS) { + return rv; } // ログ機構は引数処理後なるはや // CLI ならログは常に標準出力へ(も)出力。 // GUI なら -C で指定。 - gLogger->UseStdout(IsCLI() ? true : log_to_console); - - // 設定を作成。コンストラクタで初期値を用意 - gConfig.reset(new Config()); + logger.reset(new Logger()); + logger->UseStdout(IsCLI() ? true : log_to_console); - // 引数で指定されたディレクトリの設定ファイルを読み込んで設定を更新 - ConfigFile file(vmdir + "nono.cfg"); - if (file.Load() == false) { - return false; + // モニタマネージャ (VM 作成より前、もしかしたら Config より前?) + pMonitorManager.reset(new MonitorManager()); + gMonitorManager = pMonitorManager.get(); + + // 設定を作成。 + // c0. コンストラクタで初期値を用意。 + pConfig.reset(new Config()); + gConfig = pConfig.get(); + + // c1. ホームディレクトリに設定ファイルがあれば読み込んで設定を更新。 + struct passwd *passwd = getpwuid(getuid()); + // 見付からないことはないはずだが、一応。 + if (passwd != NULL) { + std::string filename = std::string(passwd->pw_dir) + "/.nono.cfg"; + ConfigFile dotfile(filename); + if (dotfile.Load()) { + if (gConfig->Update(dotfile) == false) { + return EXIT_FAILURE; + } + } } - if (gConfig->Update(file) == false) { - return false; + + // c2. VM ディレクトリに設定ファイルがあれば読み込んで設定を更新。 + // vmfile が存在するかどうかはここで調べるまで分からない。 + ConfigFile cfgfile(vmfile); + if (cfgfile.Load()) { + if (gConfig->Update(cfgfile) == false) { + return EXIT_FAILURE; + } } - // 最後にコマンドライン引数で更新 - if (gConfig->Update(config_options) == false) { - return false; + + // c3. 最後にコマンドライン引数で更新 + for (const auto& pair : config_options) { + if (gConfig->Update(pair.first, pair.second) == false) { + return EXIT_FAILURE; + } } - // VM 種別を決定 - if (IsCLI() && human68k_file) { - vmtype = VMTYPE_RXZ; + // MSX-DOS モードならここでいくつかパラメータを強制的に変更。 + if (msxdos_mode) { + // LUNA-I 最小構成でいい + gConfig->Update("vmtype=luna", "-S"); + gConfig->Update("ram-size=16", "-S"); + gConfig->Update("luna-video-plane=1", "-S"); + // ホスト側には干渉しない。 + gConfig->Update("hostcom-driver=none", "-S"); + gConfig->Update("hostnet-driver=none", "-S"); + } + + // 0. VM 種別を決定 + // VM 種別文字列から vmtype を決定 + const ConfigItem& item = gConfig->Find("vmtype"); + vmstr = string_tolower(item.AsString()); + if (vmstr == "x68030") { + vmtype = VMType::X68030; + } else if (vmstr == "luna") { + vmtype = VMType::LUNA1; + } else if (vmstr == "luna88k") { + vmtype = VMType::LUNA88K; + } else if (vmstr == "news") { + vmtype = VMType::NEWS; } else { - // VM 種別文字列から vmtype を決定 - const ConfigItem& item = gConfig->Get("vmtype"); - std::string vmstr = string_tolower(item.AsString()); - if (vmstr == "x68030") { - vmtype = VMTYPE_X68030; - } else if (vmstr == "luna") { - vmtype = VMTYPE_LUNA; - } else if (vmstr == "luna88k") { - vmtype = VMTYPE_LUNA88K; + if (item.GetFrom() == ConfigItem::FromInitial) { + // 未指定の時 + warnx("vmtype must be specified"); } else { - if (item.GetFrom() == ConfigItem::FromInitial) { - // 未指定の時 - warnx("vmtype must be specified"); - } else { - // ユーザ由来の時 - item.Err("invalid vmtype"); - } - return false; + // ユーザ由来の時 + item.Err("Invalid vmtype"); } + return EXIT_FAILURE; } - // VM 作成 + // 0.5. VM が確定したところで SRAM 作成。 + if (create_sram) { + if (vmtype == VMType::X68030) { + return CreateSRAM(); + } else { + warnx("--create-sram is only for X68030 mode"); + return EXIT_FAILURE; + } + } + + // 1. VM 作成 switch (vmtype) { - case VMTYPE_X68030: - gVM.reset(new VM_X68030()); + case VMType::X68030: + pVM.reset(new VM_X68030()); break; - case VMTYPE_LUNA: - gVM.reset(new VM_LUNA()); + case VMType::LUNA1: + pVM.reset(new VM_LUNA1()); break; - case VMTYPE_RXZ: - gVM.reset(new VM_RXZ()); + case VMType::LUNA88K: + pVM.reset(new VM_LUNA88K()); break; - case VMTYPE_LUNA88K: - gVM.reset(new VM_LUNA88K()); + case VMType::NEWS: + pVM.reset(new VM_NEWS()); break; default: - __unreachable(); + PANIC("corrupted vmtype=%s", vmstr.c_str()); } + gVM = pVM.get(); - // 設定内容表示 - // (MPU コンストラクタでクロック数の初期値を決めるため、その後で表示) - if (show_config) { - gConfig->Show(); + // 2. 動的なコンストラクション + if (!gVM->Create()) { + pVM.reset(); + return EXIT_FAILURE; } - // 動的なコンストラクション - if (!gVM->Create()) { - return false; + // 3. ログの処理 + + // 設定内容を表示して終了 + // (VM コンストラクタで変数の増減があるのでそれより後、 + // Create() でも SCSI パラメータを減らすので、それより後) + if (gConfig->Fix() == false) { + pVM.reset(); + return EXIT_SUCCESS; + } + if (show_config) { + gConfig->Show(show_config - 1); + pVM.reset(); + return EXIT_SUCCESS; } // ログレベルを設定。コンストラクト後すぐに行う。 // -L help もここで処理。 if (!ParseLogopt()) { - return false; + pVM.reset(); + return EXIT_FAILURE; } - return true; + return PASS; } -// VM の実行部分。 -// Init() で引数を受け付けてから Start() でデバッガスレッドなどを起動するが、 +// VM の初期化、ステージ2。スレッド生成を伴う。 +// Init1() で引数を受け付けてから Init2() でデバッガスレッドなどを起動するが、 // -Mhelp とかが指定された場合はここでスレッド開始する前にプロセスを終了する -// 必要があるので、分けてある。 +// 必要があるので分けてある。wxapp.cpp も参照。 bool -MainApp::Start() +MainApp::Init2() { - // VM 初期化。 - // これ以降はスレッドを開始したかもしれないので false を返す際には - // VM をデストラクトすること。 + // 5. VM 初期化。 if (!gVM->Init()) { - gVM.reset(); return false; } - // デバッガは VM オブジェクトリストに入っていない - debugger_init(); - // 起動時設定の適用 + // メインスレッド名を設定 + PTHREAD_SETNAME("Main"); + + // 6. スレッド開始 + if (!gVM->StartThread()) { + return false; + } + + // 7. 起動時設定の適用 if (!gVM->Apply()) { - gVM.reset(); return false; } @@ -189,38 +326,40 @@ MainApp::Start() // コマンドライン引数を処理する。 // 知らない引数とかがあればこちらで usage を表示して false を返す。 -bool +// 戻り値は、MainApp::PASS なら実行を継続、 +// EXIT_SUCCESS/EXIT_FAILURE ならこのコードで終了。 +int MainApp::ParseOpt(int ac, char *av[]) { + struct stat st; + const char *cpath; int b; int c; - fontsize = 12; - screen_scale = 1.0; - debug_breakaddr = 0xffffffff; + cpath = "."; - while ((c = getopt_long(ac, av, "A:b:B:c:CdDfhL:M:s:vV:X:", + while ((c = getopt_long(ac, av, "b:B:c:CdDfhHL:M:s:SvV:X:", longopts, NULL)) != -1) { switch (c) { - case 'A': - host_file = optarg; - break; - case 'b': - debug_breakaddr = (uint32)strtoul(optarg, NULL, 16); + debug_breakaddr.push_back(optarg); break; case 'B': b = atoi(optarg); if (b < 2 || b > 6) { fprintf(stderr, "-B : 2..6\n"); - return false; + return EXIT_FAILURE; } benchmark_mode = b; break; case 'c': - vmdir = std::string(optarg); + cpath = optarg; + // 空文字列なら再び初期値に + if (cpath[0] == '\0') { + cpath = "."; + } break; case 'C': @@ -232,18 +371,21 @@ MainApp::ParseOpt(int ac, char *av[]) break; case 'D': - debug_on_console = true; + // -D は -V debugger-driver=stdio と等価。 + config_options.emplace_back("debugger-driver=stdio", "-D"); break; case 'f': - fast_mode = true; + // -f は -V fast-mode=1 と等価。 + config_options.emplace_back("fast-mode=1", "-f"); + break; + + case 'H': + human_mode = true; break; case 'L': - if (logopt[0] != '\0') { - strlcat(logopt, ",", sizeof(logopt)); - } - strlcat(logopt, optarg, sizeof(logopt)); + AddLogopt(optarg); break; case 'M': @@ -254,29 +396,26 @@ MainApp::ParseOpt(int ac, char *av[]) break; case 's': - if (IsGUI()) { - char *end; - errno = 0; - screen_scale = strtod(optarg, &end); - if (end == optarg || end[0] != '\0' || errno == ERANGE) { - warnx("-s: invalid argument"); - return false; - } - // 上限は適当 - if (screen_scale <= 0.0 || screen_scale >= 10.0) { - warnx("-s: invalid scale"); - return false; - } - } + { + auto line = string_format("mainview-scale=%s", optarg); + config_options.emplace_back(line, "-s"); + break; + } + + case 'S': + msxdos_mode = true; break; case 'X': - human68k_file = optarg; + load_and_exec = true; + FALLTHROUGH; + case OPT_load_only: + exec_file = optarg; for (int i = optind; i < ac; i++) { if (i != optind) { - strlcat(human68k_arg, " ", sizeof(human68k_arg)); + exec_arg += " "; } - strlcat(human68k_arg, av[i], sizeof(human68k_arg)); + exec_arg += av[i]; } optind = ac; break; @@ -286,34 +425,96 @@ MainApp::ParseOpt(int ac, char *av[]) exit(0); case 'V': - config_options.push_back(optarg); + config_options.emplace_back(optarg, "-V"); + break; + + case OPT_create_sram: + create_sram = true; break; case OPT_fontsize: - fontsize = atoi(optarg); + { + auto line = string_format("monitor-fontsize=%s", optarg); + config_options.emplace_back(line, "--fontsize"); break; + } case OPT_help: ShowHelp(true); - return false; + return EXIT_SUCCESS; + + case OPT_perf: + // パフォーマンス確認用。 + // -Vprom-image=PROM.DAT はパスの問題があるので各自で追加指定 + // する必要がある。 + config_options.emplace_back(".rtc-force-fixed=1", "--perf"); + config_options.emplace_back("clock-sync=virtual", "--perf"); + config_options.emplace_back("ethernet-macaddr=02:00:00:00:00:01", + "--perf"); + config_options.emplace_back("hostcom-driver=none", "--perf"); + config_options.emplace_back("hostnet-driver=none", "--perf"); + config_options.emplace_back("luna-dipsw1=11110111", "--perf"); + config_options.emplace_back("spc0-id0-writeignore=1", "--perf"); + config_options.emplace_back("spc0-id1-writeignore=1", "--perf"); + config_options.emplace_back("spc0-id2-writeignore=1", "--perf"); + config_options.emplace_back("spc0-id3-writeignore=1", "--perf"); + config_options.emplace_back("spc0-id4-writeignore=1", "--perf"); + config_options.emplace_back("spc0-id5-writeignore=1", "--perf"); + config_options.emplace_back("spc0-id6-writeignore=1", "--perf"); + config_options.emplace_back("fast-mode=1", "--perf"); + // -C + log_to_console = true; + break; case OPT_show_config: - show_config = true; + show_config = 1; + break; + + case OPT_show_config_all: + show_config = 2; break; + case OPT_show_hostnet: + ShowHostnet(); + return EXIT_SUCCESS; + case 'h': + ShowHelp(false); + return EXIT_SUCCESS; + default: ShowHelp(false); - return false; + return EXIT_FAILURE; } } - // vmdir に '/' を付けておく - if (vmdir.empty()) { - vmdir = "."; - } - if (vmdir.back() != '/') { - vmdir += '/'; + // 引数がディレクトリなら、それを VM ディレクトリとし、その中の + // nono.cfg を設定ファイルとする。 + // 引数がファイルなら、それを設定ファイルとし、そのファイルがある + // ディレクトリを VM ディレクトリとする。 + // -c DIR => vmdir = DIR, vmfile = DIR/nono.cfg + // -c DIR/FILE => vmdir = DIR, vmfile = FILE + if (stat(cpath, &st) < 0) { + warn("stat %s", cpath); + return EXIT_FAILURE; + } + if (S_ISDIR(st.st_mode)) { + vmdir = std::string(cpath); + if (vmdir.back() != '/') { + vmdir += '/'; + } + vmfile = vmdir + "nono.cfg"; + } else if (S_ISREG(st.st_mode)) { + vmfile = std::string(cpath); + auto pos = vmfile.rfind('/'); + if (pos != std::string::npos) { + vmdir = vmfile.substr(0, pos + 1); + } else { + vmdir = "./"; + } + } else { + warnx("-c %s: path must be file or directory", cpath); + return EXIT_FAILURE; } // CLI 版で -Mhelp つけても黙って起動するのはさすがにどうかと思う。 @@ -323,15 +524,38 @@ MainApp::ParseOpt(int ac, char *av[]) if (IsCLI()) { if (monitor_opt == "help") { warnx("-Mhelp is not available on CLI"); - return false; + return EXIT_FAILURE; } if (!monitor_opt.empty()) { warnx("-M option is ignored on CLI"); - return true; + return EXIT_FAILURE; } } - return true; + // Human モード、MSX-DOS モードでは実行ファイル名が必要 + if (human_mode) { + if (exec_file == NULL) { + warnx("-H option needs -X"); + return EXIT_FAILURE; + } + } + if (msxdos_mode) { + if (exec_file == NULL) { + warnx("-S option needs -X"); + return EXIT_FAILURE; + } + } + + // 実行ファイルは、ファイル名を間違えたくらいならここでエラーに出来る。 + if (exec_file) { + int r = access(exec_file, R_OK); + if (r != 0) { + warn("-X %s", exec_file); + return EXIT_FAILURE; + } + } + + return MainApp::PASS; } // バージョンを表示 @@ -343,121 +567,405 @@ MainApp::ShowVersion() const NONO_MAJOR_VER, NONO_MINOR_VER, NONO_PATCH_VER, NONO_DATE); } +// ログレベル指定文字列を logopt に追加する。 +void +MainApp::AddLogopt(const char *opt) +{ + if (logopt.empty() == false) { + logopt += ','; + } + logopt += opt; +} -// 引数 logopt のログ指定文字列をパースする。 -// arg は "foo=1,bar=2" 形式の文字列で、これを分解して -// それぞれ担当するオブジェクトのログレベルにセットする。 +// ログレベル指定文字列を処理する。 +// str はログレベル指定文字列を ',' で連結した "foo=1,bar=2" 形式の文字列で、 +// これを分解してそれぞれ担当するオブジェクトのログレベルにセットする。 +// "help" があれば設定は行わず一覧を表示。 bool MainApp::ParseLogopt() { - char *buf; - char *last; - char *p; - bool rv; - - // "help" (完全一致) なら識別子一覧を表示。 - if (strcmp(logopt, "help") == 0) { - for (auto& obj : gObjects) { - if (obj->logname != "?") { - printf("%s\n", obj->logname.c_str()); - } - } - // エイリアスとか - printf("sch -> scheduler\n"); - if (vmtype == VMTYPE_LUNA) { - printf("scc -> sio\n"); + std::vector items; + + // 分解して.. + items = string_split(logopt.c_str(), ','); + + // "help" があればヘルプを表示して終了 + for (const auto& item : items) { + if (item == "help") { + std::vector list = GetLogNames(); + // less したいだろうから stderr ではなく stdout に出力する + for (const auto& name : list) { + printf(" %s\n", name.c_str()); + } + return false; } - printf("all\n"); + } + + // ログレベルを設定 + std::string errmsg; + if (SetLogopt(items, &errmsg) == false) { + warnx("%s", errmsg.c_str()); return false; } - rv = false; - buf = strdup(logopt); - for (p = strtok_r(buf, ",", &last); - p; - p = strtok_r(NULL, ",", &last)) - { - const char *name; - char *v; - int val; - - name = p; - - v = strchr(p, '='); - if (v) { - *v++ = '\0'; - val = atoi(v); - } else { - val = 1; + return true; +} + +// ログレベルを設定する。 +// ログレベル指定文字列を 1つずつに分解したリスト items を処理する。 +// "help" があるケースはここに来るまでに処理してあるので、ここには来ない。 +// 成功なら何も表示せず true を返す。失敗なら *errmsg にエラーメッセージを +// 格納して false を返す。 +// MainApp 内と Debugger からも呼ばれる。 +/*static*/ bool +MainApp::SetLogopt(const std::vector& items, std::string *errmsg) +{ + for (const auto& item : items) { + if (SetLogopt1(item.c_str(), errmsg) == false) { + return false; + } + } + if (0) { // デバッグ用 + for (const auto o : gMainApp.GetObjects()) { + printf("%-16s %d\n", o->GetName().c_str(), o->loglevel); } - // ここで name は変数名、val は値(省略されたら1) + } + return true; +} + +// "logname[=loglevel]" 形式をパースしてオブジェクトにログレベルを設定する。 +// loglevel は省略なら 1 とする。 +// logname が "all" なら全オブジェクトにセットする。 +// そうでない場合は case ignore で完全一致するか前方一致で1つに確定すれば、 +// そのオブジェクトにログレベルを設定して true を返す。 +// 見付からないか候補が複数ある場合はエラーメッセージを *errmsg に出力して +// false を返す。 +// この関数は (このすぐ上の SetLogopt() を経由して) +// MainApp と Debugger から呼ばれることに注意。 +/*static*/ bool +MainApp::SetLogopt1(const std::string& item, std::string *errmsg) +{ + std::string name; + const char *v; + int level; + + v = strchr(item.c_str(), '='); + if (v) { + name = std::string(item.c_str(), v - item.c_str()); + level = atoi(++v); + } else { + name = item; + level = 1; + } + // ここで name は変数名、level は値(省略されたら1) + + if (name.empty()) { + *errmsg = "logname must be specified"; + return false; + } - if (strlen(name) < 1) { - printf("invalid logname '%s'\n", name); - goto abort; + // 今の所、値域は -1 〜 9 ということにしておく。 + if (level < -1) { + level = -1; + } else if (level > 9) { + level = 9; + } + + // "all" なら全部にセット + if (name == "all") { + for (auto obj : gMainApp.GetObjects()) { + if (obj->GetName().empty() == false) { + obj->SetLogLevel(level); + } } + return true; + } + // "fdd" なら "fdd*" 全部にする + if (name == "fdd") { + for (auto obj : gMainApp.GetObjects()) { + if (strncasecmp(obj->GetName().c_str(), "fdd", 3) == 0) { + obj->SetLogLevel(level); + } + } + return true; + } - // 短縮形とかエイリアスとか - if (strcmp(name, "sch") == 0) - name = "scheduler"; - if (vmtype == VMTYPE_LUNA) { - if (strcmp(name, "scc") == 0) - name = "sio"; + // エイリアスリストを作る + using aliaslist_t = std::vector>; + aliaslist_t alias_list; + for (const auto& obj : gMainApp.GetObjects()) { + const std::vector& aliases = obj->GetAliases(); + + for (const auto& a : aliases) { + alias_list.emplace_back(a, obj); } + } - // 比較 - if (strcmp(name, "all") == 0) { - // "all" なら none 以外の全部にセット - for (auto& obj : gObjects) { - obj->loglevel = val; + // エイリアスを完全一致のみのものと部分一致も許容するものに分ける + aliaslist_t exact_alias; + aliaslist_t partial_alias; + for (const auto& a0 : alias_list) { + bool exact = false; + for (const auto& a1 : alias_list) { + if (a0.first == a1.first) { + continue; + } + if (starts_with_ignorecase(a0.first, a1.first)) { + exact = true; + break; } + } + if (exact) { + exact_alias.push_back(a0); } else { - // それ以外は一致するキーを探してセット - std::string sname = name; - bool found = false; - for (auto& obj : gObjects) { - if (obj->logname == sname) { - obj->loglevel = val; - found = true; - break; - } + partial_alias.push_back(a0); + } + } + + // 完全一致をまず調べる + for (const auto& a : exact_alias) { + if (strcasecmp(a.first.c_str(), name.c_str()) == 0) { + a.second->SetLogLevel(level); + return true; + } + } + + aliaslist_t found; + for (const auto& a : partial_alias) { + // 前方一致したら覚えておく + if (starts_with_ignorecase(a.first, name)) { + found.push_back(a); + } + } + + // 見付からない場合はエラー + if (found.empty()) { + *errmsg = string_format("Unknown logname \"%s\"", name.c_str()); + return false; + } + + // 1つだけなら確定 + if (found.size() == 1) { + found[0].second->SetLogLevel(level); + return true; + } + + // 複数あれば候補文字列を作成 + *errmsg = string_format("Ambiguous logname \"%s\": candidates are", + name.c_str()); + for (const auto& cand : found) { + *errmsg += string_format(" \"%s\"", cand.first.c_str()); + } + return false; +} + +// ログ名の一覧を取得する。 +// MainApp と Debugger から呼ばれる。 +/*static*/ std::vector +MainApp::GetLogNames() +{ + std::vector sortobj; + + // エイリアスを持つオブジェクトだけ抜き出す + for (const auto& obj : gMainApp.GetObjects()) { + if (obj->GetAliases().empty() == false) { + sortobj.emplace_back(obj); + } + } + + // aliases の一語目で sortobj をソートする + std::sort(sortobj.begin(), sortobj.end(), + [](const auto a, const auto b) { + const auto& sa = a->GetAliases()[0]; + const auto& sb = b->GetAliases()[0]; + return sa < sb; + } + ); + + std::vector list; + for (const auto *obj : sortobj) { + const auto& aliases = obj->GetAliases(); + std::string str; + + str = aliases[0]; + if (aliases.size() > 1) { + str += " (alias:"; + for (int i = 1, sz = aliases.size(); i < sz; i++) { + str += ' '; + str += aliases[i]; } - // 見つからない場合はエラー - if (!found) { - printf("invalid logname '%s'\n", name); - goto abort; - } - } + str += ')'; + } + list.emplace_back(str); } + list.emplace_back("all"); - rv = true; - abort: - free(buf); - return rv; + return list; } // 関連するファイルのパスを取得。 +// 1. name がファイル名のみなら、VM ディレクトリとその親ディレクトリを検索。 +// ファイルが存在すればその時点で戻り値とする。ファイルが存在したけど +// 何らか不都合があったとしても (例えばファイルサイズが 0 だとか +// パーミッションが足りないとか) 次を試すとかはしない。 +// 2. name が '~' から始まっていればホームディレクトリに展開。 +// 3. name が相対パスなら VM ディレクトリからの相対パスとする。 +// 4. name は絶対パスのはずなので、そのまま使用する。 std::string MainApp::SearchFile(const std::string& name) const { std::string path; struct stat st; - // ファイルがあるかどうかを調べるだけで、存在したけどそれに何らか - // 不都合があったら次を試すとかはしない。 + // 1. パス区切りを含んでなければ、ファイル名のみ + if (name.find('/') == std::string::npos) { + // 1a. VM ディレクトリ + path = GetVMDir() + name; + if (stat(path.c_str(), &st) == 0) { + return path; + } - // 1. 設定ファイルディレクトリ - path = GetVMDir() + name; - if (stat(path.c_str(), &st) == 0) { - return path; + // 2. 親ディレクトリ + path = GetVMDir() + "../" + name; + if (stat(path.c_str(), &st) == 0) { + return path; + } + + // どちらもなければエラー + return ""; + } + + // 2. 先頭の '~' を $HOME に展開 + path = name; + if (path[0] == '~' && path[1] == '/') { + const char *home = getenv("HOME"); + if (home == NULL) { + home = ""; + } + path = string_format("%s%s", home, path.c_str() + 1); + } + + // 3. 相対パスなら、VM ディレクトリからの相対 + if (path[0] != '/') { + path = GetVMDir() + path; + } + + return path; +} + +// 初回起動時用に SRAM.DAT を作成する。 +// 戻り値は EXIT_SUCCESS / EXIT_FAILURE。 +int +MainApp::CreateSRAM() +{ + char buf[16 * 1024]; + std::string filename; + autofd fd; + int r; + + filename = GetVMDir() + "SRAM.DAT"; + + // 存在確認のため一旦読み込み専用で開いてみる。 + // オープン出来たら何もしない。 + fd = open(filename.c_str(), O_RDONLY); + if (fd >= 0) { + warnx("%s: Already exists", filename.c_str()); + return EXIT_FAILURE; + } + + fd = open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644); + if (fd < 0) { + warn("%s: open failed", filename.c_str()); + return EXIT_FAILURE; } - // 2. 共通ディレクトリ(?) - // XXX 共通ディレクトリを返す関数を用意したほうがいいか - path = GetVMDir() + "../" + name; - if (stat(path.c_str(), &st) == 0) { - return path; + memset(&buf[0], 0, sizeof(buf)); + for (int i = 0; i < SRAMDevice::InitialData.size(); i++) { + buf[i] = SRAMDevice::InitialData[i]; } - return ""; + r = write(fd, buf, sizeof(buf)); + if (r < 0) { + warn("%s: write failed", filename.c_str()); + return EXIT_FAILURE; + } + + fd.Close(); + warnx("created %s", filename.c_str()); + return EXIT_SUCCESS; +} + +// 現在の VM が指定のケーパビリティを持っているか? +bool +MainApp::Has(VMCap cap) const +{ + uint32 vmcap = 1U << (int)GetVMType(); + return (vmcap & (uint32)cap) != 0; +} + +// コンパイルされている host netdriver の一覧を表示。 +void +MainApp::ShowHostnet() const +{ + auto list = HostNetDevice::GetDrivers(); + for (const auto& name : list) { + printf(" %s\n", name.c_str()); + } +} + +// オブジェクト登録 +void +MainApp::RegistObject(Object *obj) +{ + // ID が重複していないかチェック (NONE なら重複可) + auto id = obj->GetId(); + if (id != OBJ_NONE) { + if (FindObject(id)) { + PANIC("%s already exists", Object::GetIdStr(id)); + } + } + + obj->logger = gMainApp.GetLogger(); + + objects.push_back(obj); +} + +// オブジェクト削除 +void +MainApp::UnregistObject(Object *obj) +{ + // 最初に見付かった一つを削除するだけでいい + for (auto it = objects.begin(); it != objects.end(); ++it) { + if (*it == obj) { + objects.erase(it); + break; + } + } +} + +// 指定された id を持つオブジェクトを返す。なければ NULL を返す。 +Object * +MainApp::FindObject(int id) const +{ + // NONE はここで検索しない (SCSI デバイスなど、そっちで検索する) + if (id == OBJ_NONE) { + return NULL; + } + for (auto obj : objects) { + if (obj->GetId() == id) { + return obj; + } + } + return NULL; +} + +// 指定された id を持つオブジェクトを探す。なければ assert する。 +Object * +MainApp::GetObject(int id) const +{ + Object *obj = FindObject(id); + if (__predict_false(obj == NULL)) { + PANIC("objid=%s not found", Object::GetIdStr(id)); + } + return obj; }