From a2d1d590a550dcbf5465db2399f2d087efd0443a Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sun, 15 Nov 2026 23:18:13 +0800 Subject: [PATCH] Install lldb-dap from the plugin details with Homebrew (0.1.0) When neither PATH nor `xcrun --find lldb-dap` has lldb-dap, the debug capability card now offers an install button: a command installer runs `brew install lldb` through a plugin-qualified Homebrew tool definition (brew on PATH, /opt/homebrew or /usr/local) and reads the directory from `brew --prefix lldb` plus bin. Only the toolDefault target is declared, since Homebrew owns where LLDB goes. The manifest now requires commandInstallers and toolDefinitions and asks for commands.install. Homebrew's llvm formula no longer builds LLDB. The separate lldb formula is keg-only, depends on llvm and Python, and is built with LLDB_USE_SYSTEM_DEBUGSERVER, so it launches programs through the Command Line Tools' debugserver. The docs say what the install downloads, that Homebrew ships bottles only for Apple Silicon on macOS 15 and later (elsewhere it builds from source and can run past the one-hour limit), and how to remove it. scripts/test.mjs builds a C program with clang -g and runs two real DAP sessions as the manifest declares them: one with the lldb-dap Lithe finds today and one after the declared install, each stopping on a breakpoint, reading a local and exiting cleanly. CI runs it on macos-latest. The host e2e pin moves to 1lck/Lithe-IDEA 4032c5ca0, which serves commandInstallers, and the test validates with the host's declared capabilities instead of a hard-coded list. --- .github/workflows/ci.yml | 19 ++ .github/workflows/release.yml | 3 +- README.md | 42 ++- docs/releases/v0.1.0.md | 25 ++ .../workbench/debug_native_e2e_test.go | 7 +- e2e/host/lithe-host.json | 2 +- io.github.lithe-idea.lldb-debug/plugin.json | 102 ++++++- scripts/package.mjs | 3 +- scripts/test.mjs | 250 ++++++++++++++++++ 9 files changed, 438 insertions(+), 15 deletions(-) create mode 100644 docs/releases/v0.1.0.md create mode 100644 scripts/test.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a876d01..1e5cc88 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -35,3 +35,22 @@ jobs: } process.exit(failed ? 1 : 0); " + + # The declared debug adapter and lldb-dap installer with the real programs on + # macOS: a debug session with the lldb-dap Lithe finds today (Xcode's, through + # xcrun), the declared `brew install lldb`, and a session with the lldb-dap it + # installed. + commands: + runs-on: macos-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - name: Debug with the system lldb-dap, then install lldb-dap with Homebrew and debug with it + run: | + xcrun --find lldb-dap + brew --version + brew list --versions lldb llvm || echo "lldb is not installed yet" + node scripts/test.mjs diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index dce74c2..71a28e8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -30,7 +30,8 @@ jobs: GH_TOKEN: ${{ github.token }} # v0.0.1 follows plugin contract v0, which only the new desktop # client installs, and that client ships as desktop-v* pre-releases. - PRERELEASE_TAGS: v0.0.1 + # v0.1.0 also needs a desktop client with commandInstallers. + PRERELEASE_TAGS: v0.0.1 v0.1.0 run: | prerelease=false for tag in $PRERELEASE_TAGS; do diff --git a/README.md b/README.md index 955e1c2..7fe0a40 100644 --- a/README.md +++ b/README.md @@ -11,20 +11,39 @@ > `debugAdapters` contract; it is a single `plugin.json` and carries no debugger. > **预发布**:按插件契约 v0(`schemaVersion: 0`、`pluginAPIVersion: 0`)编写,只能装进新版 Lithe 桌面端 -> (`desktop-v*` 预发布),旧版 macOS Lithe 无法安装。 +> (`desktop-v*` 预发布),旧版 macOS Lithe 无法安装。0.1.0 起插件声明了 `lldb-dap` 的安装方式,需要支持 +> `commandInstallers` 的桌面端([1lck/Lithe-IDEA#1971](https://github.com/1lck/Lithe-IDEA/pull/1971));更早的桌面端请用 0.0.1。 ## 依赖的程序 -- `lldb-dap`。Lithe 先在 `PATH` 里找,找不到时在 macOS 上用 `xcrun --find lldb-dap` 找 Xcode 自带的版本。 - 可以用 `xcode-select --install` 安装 Xcode 命令行工具,或者安装 Xcode 或 LLVM。 +- `lldb-dap`。Lithe 先在 `PATH` 里找,找不到时在 macOS 上用 `xcrun --find lldb-dap` 找 Xcode 自带的版本, + 再找在 Lithe 里安装时记下的目录。Xcode 和 Xcode 命令行工具(`xcode-select --install`)都带 `lldb-dap`; + 都没有时可以在 Lithe 里用 Homebrew 安装,见[在 Lithe 里安装 lldb-dap](#在-lithe-里安装-lldb-dap)。 - 带调试信息的程序,例如 `clang -g main.c -o main`(`gcc -g` 也可以)。 +### 在 Lithe 里安装 lldb-dap + +1. 打开 **设置 → 插件 → 已安装**,选中 LLDB Debugger,切到 **功能**。 +2. 找不到 `lldb-dap` 时,调试能力卡片上显示“未找到 lldb-dap”,旁边有 **安装** 按钮。 +3. 点击后核对要运行的命令,确认后开始安装,输出显示在对话框里。Lithe 用 Homebrew 运行 `brew install lldb`, + 装好后在 `$(brew --prefix lldb)/bin` 里找到 `lldb-dap` 并记下这个目录,之后调试直接用它,不需要改 `PATH`。 + +需要先装好 [Homebrew](https://brew.sh)(它会一并要求 Xcode 命令行工具;Homebrew 的 LLDB 用命令行工具里的 +`debugserver` 启动程序)。Lithe 在 `PATH`、`/opt/homebrew` 和 `/usr/local` 里找 `brew`。安装需要联网,会下载 LLDB +和它依赖的 LLVM、Python(几百 MB,装好后超过 1 GB),通常几分钟。Homebrew 只给 Apple Silicon 上的 macOS 15 及以上 +提供预编译包;Intel Mac 和更早的 macOS 上会从源码编译,可能超过一小时的安装时限,这时请改用 Xcode 或命令行工具自带的 +`lldb-dap`。LLDB 和 LLVM 都是 keg-only,不会链接进 `/opt/homebrew/bin`,也不会替换系统的 `lldb`、`clang`。 +安装位置是 Homebrew 自己的目录,卸载插件时不删除,不需要时用 `brew uninstall lldb` 删掉,再用 `brew autoremove` +删掉不再需要的依赖。也可以自己在终端运行 `brew install lldb`,再把 `$(brew --prefix lldb)/bin` 加进 Lithe 能看到的 +`PATH`。 + ## 安装 1. 从 [Releases](https://github.com/Lithe-IDEA/lithe-plugin-lldb/releases) 下载 `lldb-debug-<版本>-darwin.zip`。 2. 在 Lithe 中打开 **设置 → 插件**,点击页面标题栏右侧的 **从文件安装…**,选中这个 zip,核对 SHA-256 和权限后确认。 -插件会请求 `debug.launch` 权限,用来启动你电脑上的 `lldb-dap`。装好后打开 C / Rust / Swift 文件,设置断点并开始调试。 +插件会请求 `debug.launch` 权限,用来启动你电脑上的 `lldb-dap`;还会请求 `commands.install` 权限, +只在你点击 **安装** 并确认后用 Homebrew 安装 `lldb-dap`。装好后打开 C / Rust / Swift 文件,设置断点并开始调试。 ## 可执行文件设置 @@ -53,9 +72,10 @@ Program 设置按项目保存,修改后从下一次调试开始生效。 ```text io.github.lithe-idea.lldb-debug/plugin.json # 插件描述,目录名必须等于插件 id scripts/package.mjs # 校验清单,打包成 dist/lldb-debug-<版本>-darwin.zip +scripts/test.mjs # 用真实的 lldb-dap 和 Homebrew 运行清单声明的调试和安装 scripts/e2e-host.mjs # 在固定版本的宿主里运行 e2e/host/ 的测试 e2e/host/ # 宿主端到端测试和宿主版本固定文件 lithe-host.json -.github/workflows/ci.yml # PR 时打包,并用 Lithe Store 的规则检查 +.github/workflows/ci.yml # PR 时打包、用 Lithe Store 的规则检查,并在 macOS 上运行 scripts/test.mjs .github/workflows/release.yml # 推送 v<版本> 标签时发布 GitHub Release docs/releases/v<版本>.md # 该版本的变化,发布时并入 Release 说明(可选) ``` @@ -68,6 +88,14 @@ node scripts/package.mjs 本地开发时,用 **设置 → 插件 → 从文件安装…** 选择 `dist/lldb-debug-<版本>-darwin.zip` 安装。 +`scripts/test.mjs` 用 `clang -g` 编译一个 C 程序,按清单的声明启动调试:先用 `PATH` 或 `xcrun` 找到的 `lldb-dap` +命中断点、读出局部变量并运行到退出,再按安装器的声明用 Homebrew 运行 `brew install lldb`,从目录探针给出的目录启动 +装好的 `lldb-dap` 再调试一次。安装会下载 LLDB 和 LLVM,本地只想测调试时设 `LITHE_TEST_INSTALL=0`: + +```bash +LITHE_TEST_INSTALL=0 node scripts/test.mjs +``` + `plugin.json` 的完整格式见 Rust Core 仓库里的 [插件契约](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/shared/plugins/contract/v1/README.md) 和[调试适配器插件指南](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/shared/plugins/guides/debug-adapter-plugin.md)。 @@ -98,11 +126,11 @@ Rust Core,`LITHE_CORE_RUST_DIR` 可以指向本地的 Core 检出。`--ref < 2. 推送同名标签: ```bash - git tag v0.0.1 && git push origin v0.0.1 + git tag v0.1.0 && git push origin v0.1.0 ``` 3. `Release` 工作流会核对标签与版本、打包并发布 Release(说明里附 SHA-256)。`release.yml` 里 `PRERELEASE_TAGS` - 列出的版本会标为预发布版本:目前是只能装进新版桌面端的 `v0.0.1`。 + 列出的版本会标为预发布版本:目前是只能装进新版桌面端的 `v0.0.1` 和 `v0.1.0`。 4. Lithe Store 的自动追踪会发现稳定版本并开合并请求。自动追踪会跳过预发布版本;需要收录时在 Store 中手工提交条目, 并使用已发布 ZIP 的实际 SHA-256。 diff --git a/docs/releases/v0.1.0.md b/docs/releases/v0.1.0.md new file mode 100644 index 0000000..adfe6aa --- /dev/null +++ b/docs/releases/v0.1.0.md @@ -0,0 +1,25 @@ +0.1.0 可以在 Lithe 里安装 `lldb-dap`。 + +功能: +- 找不到 `lldb-dap` 时(`PATH` 和 `xcrun --find lldb-dap` 都没有),插件详情里调试能力的卡片上有 **安装** 按钮: + Lithe 用 Homebrew 运行 `brew install lldb`,装好后在 `$(brew --prefix lldb)/bin` 里找到 `lldb-dap` 并记下这个目录, + 之后调试直接用它,不需要改 `PATH`。 +- 需要先装好 Homebrew;Lithe 在 `PATH`、`/opt/homebrew` 和 `/usr/local` 里找 `brew`。安装需要联网,会下载 LLDB 和它依赖的 + LLVM、Python(几百 MB,装好后超过 1 GB),最长等一小时。LLDB 和 LLVM 都是 keg-only,不会替换系统的 `lldb`、`clang`, + 卸载插件时也不删除。 +- Homebrew 只给 Apple Silicon 上的 macOS 15 及以上提供预编译包;Intel Mac 和更早的 macOS 上会从源码编译,可能超过 + 一小时的时限,这时请用 Xcode 或命令行工具自带的 `lldb-dap`。 +- 已经有 Xcode 或 Xcode 命令行工具自带的 `lldb-dap` 时,行为和 0.0.1 相同,不会出现安装按钮。 + +验证: +- CI 在 macOS 上用 `clang -g` 编译一个 C 程序,按清单的声明运行两次调试会话(`scripts/test.mjs`):一次用 `xcrun` + 找到的 Xcode 自带 `lldb-dap`,一次用按安装器声明执行 `brew install lldb` 后、从目录探针给出的目录启动的 + `lldb-dap`;两次都命中断点、读出局部变量并正常退出。 +- 清单用 Rust Core 的清单校验、工具注册、发现计划和安装计划检查过;宿主端到端测试固定到包含 `commandInstallers` 的宿主版本。 + +权限:新增 `commands.install`,只在你点击 **安装** 并确认后使用。 + +兼容性: +- 需要支持 `commandInstallers` 的 Lithe 桌面端(1lck/Lithe-IDEA#1971);更早的桌面端请继续用 0.0.1。 +- 只能装进新版 Lithe 桌面端(`desktop-v*` 预发布)。 +- 本版本是预发布,Lithe Store 的自动追踪会跳过它。 diff --git a/e2e/host/desktop/internal/workbench/debug_native_e2e_test.go b/e2e/host/desktop/internal/workbench/debug_native_e2e_test.go index 6bbcce3..b155052 100644 --- a/e2e/host/desktop/internal/workbench/debug_native_e2e_test.go +++ b/e2e/host/desktop/internal/workbench/debug_native_e2e_test.go @@ -13,6 +13,7 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/buildprocess" "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginstate" "github.com/1lck/Lithe-IDEA/desktop/internal/store" ) @@ -29,9 +30,9 @@ func TestDebugRealLLDBLaunchTargetAndBreakpoints(t *testing.T) { t.Fatal(err) } validationContext, cancelValidation := context.WithTimeout(context.Background(), 5*time.Second) - _, validationErr := core.NewClient().ValidatePluginManifest(validationContext, manifest, map[string][]int{ - "debugAdapters": {0}, "languages": {0}, "settings": {0}, - }) + // The capabilities this host serves, so the manifest is admitted the way an + // installation admits it. + _, validationErr := core.NewClient().ValidatePluginManifest(validationContext, manifest, pluginhost.Declared()) cancelValidation() if validationErr != nil { t.Fatal(validationErr) diff --git a/e2e/host/lithe-host.json b/e2e/host/lithe-host.json index b66099e..48319a3 100644 --- a/e2e/host/lithe-host.json +++ b/e2e/host/lithe-host.json @@ -1,6 +1,6 @@ { "repository": "https://github.com/1lck/Lithe-IDEA.git", - "revision": "059d878d4284e1a1fd218aeaa56c29d9753d4dfa", + "revision": "4032c5ca0fad2d2c1986ead37d719ec1f9f0502e", "packages": { "./internal/workbench": "^TestDebugRealLLDBLaunchTargetAndBreakpoints$" }, diff --git a/io.github.lithe-idea.lldb-debug/plugin.json b/io.github.lithe-idea.lldb-debug/plugin.json index dee870b..43604a9 100644 --- a/io.github.lithe-idea.lldb-debug/plugin.json +++ b/io.github.lithe-idea.lldb-debug/plugin.json @@ -2,19 +2,25 @@ "schemaVersion": 0, "id": "io.github.lithe-idea.lldb-debug", "displayName": "LLDB Debugger", - "version": "0.0.1", + "version": "0.1.0", "pluginAPIVersion": 0, "requires": { + "commandInstallers": 0, "debugAdapters": 0, "languages": 0, - "settings": 0 + "settings": 0, + "toolDefinitions": 0 }, + "requiresTools": [ + "io.github.lithe-idea.lldb-debug:homebrew" + ], "vendor": { "id": "io.github.lithe-idea", "displayName": "Lithe-IDEA", "signatureRequirement": "none" }, "permissions": [ + "commands.install", "debug.launch" ], "activationEvents": [ @@ -235,5 +241,97 @@ "transport": "stdio" } } + ], + "toolDefinitions": [ + { + "id": "io.github.lithe-idea.lldb-debug:homebrew", + "displayName": "Homebrew", + "executableLayouts": [ + { + "path": "bin/brew", + "platforms": [ + "macos" + ] + } + ], + "executables": [ + { + "id": "shell", + "kind": "command", + "command": "brew", + "platforms": [ + "macos" + ] + }, + { + "id": "detected", + "kind": "toolchain", + "scope": "installed" + } + ], + "version": { + "arguments": [ + "--version" + ], + "pattern": "Homebrew (\\d+(?:\\.\\d+)*)" + }, + "discovery": [ + { + "root": { + "kind": "absolute", + "path": "/opt" + }, + "pattern": "homebrew", + "platforms": [ + "macos" + ] + }, + { + "root": { + "kind": "absolute", + "path": "/usr" + }, + "pattern": "local", + "platforms": [ + "macos" + ] + } + ], + "commands": [ + "brew" + ], + "launch": [ + "${executable}", + "${arguments}" + ] + } + ], + "commandInstallers": [ + { + "id": "lldb-dap", + "commands": [ + "lldb-dap" + ], + "tool": "io.github.lithe-idea.lldb-debug:homebrew", + "arguments": [ + "install", + "lldb" + ], + "mayUseNetwork": true, + "timeoutSeconds": 3600, + "targets": { + "toolDefault": { + "directory": [ + { + "arguments": [ + "--prefix", + "lldb" + ], + "append": "bin" + } + ] + } + } + } ] } diff --git a/scripts/package.mjs b/scripts/package.mjs index ba6dbc4..9965729 100644 --- a/scripts/package.mjs +++ b/scripts/package.mjs @@ -4,7 +4,8 @@ // // The package is a single plugin.json: it only declares how Lithe starts the // user's own lldb-dap, so it carries no executable and one archive serves -// every Mac. Nothing is downloaded at build or install time. +// every Mac. Nothing is downloaded at build or install time; the lldb-dap +// installer it declares runs Homebrew only when the user asks for it in Lithe. // // Usage: node scripts/package.mjs [--expect-tag ] diff --git a/scripts/test.mjs b/scripts/test.mjs new file mode 100644 index 0000000..05d50fa --- /dev/null +++ b/scripts/test.mjs @@ -0,0 +1,250 @@ +#!/usr/bin/env node +// Runs what plugin.json declares with the real programs, the way Lithe runs them, on a +// C program built with clang -g under a path with a space: +// +// - a debug session with the lldb-dap Lithe finds without installing anything (PATH, +// then `xcrun --find lldb-dap`): a breakpoint stops on its line, a local variable reads +// back and the program runs to a clean exit; +// - the lldb-dap installer: Homebrew is found the way its tool definition says (brew on +// PATH, then the declared install locations), answers the version probe, runs the +// declared install, and the directory probe names the directory lldb-dap lands in; +// - the same debug session with that installed lldb-dap. +// +// LITHE_TEST_INSTALL=0 skips the install, which downloads LLDB and the LLVM it depends on +// (several hundred MB). +// +// Usage: node scripts/test.mjs + +import assert from "node:assert/strict"; +import { spawn, spawnSync } from "node:child_process"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { isAbsolute, join } from "node:path"; + +const manifest = JSON.parse(readFileSync("io.github.lithe-idea.lldb-debug/plugin.json", "utf8")); +const adapter = manifest.debugAdapters.find((entry) => entry.id === "lldb"); +const installer = manifest.commandInstallers.find((entry) => entry.id === "lldb-dap"); +const brewTool = manifest.toolDefinitions.find((entry) => entry.id === installer.tool); +const WAIT_MS = 60_000; + +function run(command, args, { cwd, timeout = 10 * 60_000 } = {}) { + const result = spawnSync(command, args, { cwd, encoding: "utf8", timeout, maxBuffer: 64 * 1024 * 1024 }); + if (result.error) throw new Error(`${command} ${args.join(" ")}: ${result.error.message}`); + if (result.status !== 0) { + throw new Error(`${command} ${args.join(" ")} exited with ${result.status ?? result.signal}\n${result.stdout}${result.stderr}`); + } + return result.stdout; +} + +let failed = false; +async function check(name, body) { + const started = Date.now(); + try { + await body(); + console.log(`✓ ${name} (${Date.now() - started} ms)`); + } catch (error) { + failed = true; + console.error(`✗ ${name}\n${error.stack}`); + } +} + +/** A Debug Adapter Protocol client over the adapter's stdio, as the stdio transport speaks it. */ +class Dap { + constructor(child) { + this.child = child; + this.seq = 1; + this.pending = new Map(); + this.events = []; + this.waiters = []; + this.log = ""; + let buffer = Buffer.alloc(0); + child.stdout.on("data", (chunk) => { + buffer = Buffer.concat([buffer, chunk]); + for (;;) { + const end = buffer.indexOf("\r\n\r\n"); + if (end < 0) return; + const length = Number(/Content-Length: *(\d+)/i.exec(buffer.subarray(0, end).toString())?.[1]); + if (buffer.length < end + 4 + length) return; + const message = JSON.parse(buffer.subarray(end + 4, end + 4 + length).toString()); + buffer = buffer.subarray(end + 4 + length); + this.receive(message); + } + }); + child.stderr.setEncoding("utf8").on("data", (chunk) => { this.log += chunk; }); + child.once("exit", (code, signal) => { + const error = new Error(`lldb-dap exited with ${code ?? signal}\n${this.log}`); + for (const { reject } of this.pending.values()) reject(error); + for (const { reject } of this.waiters) reject(error); + }); + } + + receive(message) { + if (message.type === "response") { + const pending = this.pending.get(message.request_seq); + this.pending.delete(message.request_seq); + if (message.success) pending?.resolve(message.body ?? {}); + else pending?.reject(new Error(`${message.command} failed: ${message.message ?? ""} ${JSON.stringify(message.body ?? {})}`)); + } else if (message.type === "event") { + if (message.event === "output") this.log += message.body?.output ?? ""; + this.events.push(message); + this.waiters = this.waiters.filter((waiter) => !waiter.take()); + } + } + + request(command, args = {}) { + const seq = this.seq++; + const body = JSON.stringify({ seq, type: "request", command, arguments: args }); + this.child.stdin.write(`Content-Length: ${Buffer.byteLength(body)}\r\n\r\n${body}`); + return this.within(`the ${command} response`, new Promise((resolve, reject) => this.pending.set(seq, { resolve, reject }))); + } + + /** The first event named `name` that has not been taken yet and matches `accept`. */ + event(name, accept = () => true) { + return this.within(`a ${name} event`, new Promise((resolve, reject) => { + const waiter = { + reject, + take: () => { + const index = this.events.findIndex((event) => event.event === name && accept(event.body ?? {})); + if (index < 0) return false; + resolve(this.events.splice(index, 1)[0].body ?? {}); + return true; + }, + }; + if (!waiter.take()) this.waiters.push(waiter); + })); + } + + within(what, promise) { + let timer; + const timeout = new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error(`no ${what} within ${WAIT_MS / 1000} s\n${this.log}`)), WAIT_MS); + }); + return Promise.race([promise, timeout]).finally(() => clearTimeout(timer)); + } +} + +/** Launches the program under `lldbDap` with the configuration plugin.json declares and debugs it. */ +async function debugSession(lldbDap, program, source, line) { + assert.equal(adapter.launch.transport, "stdio"); + const child = spawn(lldbDap, adapter.launch.process.arguments ?? [], { stdio: ["pipe", "pipe", "pipe"] }); + const dap = new Dap(child); + try { + await dap.request("initialize", { + clientID: "lithe-test", adapterID: adapter.adapterID, pathFormat: "path", + linesStartAt1: true, columnsStartAt1: true, + }); + // The host sends the declared arguments plus the bound program and working directory. + const { arguments: declared, targetBindings } = adapter.configurations.launch; + assert.deepEqual(targetBindings, { program: "target.executable", cwd: "target.workingDirectory" }); + const launched = dap.request("launch", { ...declared, program, cwd: join(program, "..") }); + await dap.event("initialized"); + const { breakpoints } = await dap.request("setBreakpoints", { source: { path: source }, breakpoints: [{ line }] }); + assert.equal(breakpoints.length, 1); + await dap.request("configurationDone"); + await launched; + const stopped = await dap.event("stopped"); + assert.equal(stopped.reason, "breakpoint", JSON.stringify(stopped)); + const { stackFrames } = await dap.request("stackTrace", { threadId: stopped.threadId, levels: 1 }); + assert.equal(stackFrames[0].line, line); + assert.equal(realpathSync(stackFrames[0].source.path), realpathSync(source)); + const { scopes } = await dap.request("scopes", { frameId: stackFrames[0].id }); + const locals = scopes.find((scope) => /local/i.test(scope.name)) ?? scopes[0]; + const { variables } = await dap.request("variables", { variablesReference: locals.variablesReference }); + assert.equal(variables.find((variable) => variable.name === "answer")?.value, "42", JSON.stringify(variables)); + await dap.request("continue", { threadId: stopped.threadId }); + const exited = await dap.event("exited"); + assert.equal(exited.exitCode, 0); + await dap.request("disconnect", { terminateDebuggee: true }).catch(() => {}); + } finally { + child.kill(); + } +} + +/** The lldb-dap Lithe finds before offering the installer: PATH, then xcrun on macOS. */ +function systemLldbDap() { + const command = adapter.launch.process.launch.commands[0]; + const onPath = spawnSync("/usr/bin/which", [command], { encoding: "utf8" }); + if (onPath.status === 0) return onPath.stdout.trim(); + return run("xcrun", ["--find", command]).trim(); +} + +/** Homebrew the way its tool definition finds it: brew on PATH, then the declared install locations. */ +function findBrew() { + const command = brewTool.executables.find((entry) => entry.kind === "command").command; + const onPath = spawnSync("/usr/bin/which", [command], { encoding: "utf8" }); + if (onPath.status === 0) return onPath.stdout.trim(); + const layout = brewTool.executableLayouts.find((entry) => entry.platforms.includes("macos")).path; + for (const scan of brewTool.discovery.filter((entry) => entry.platforms.includes("macos"))) { + assert.doesNotMatch(scan.pattern, /\*/, "the discovery patterns are literal directories"); + const candidate = join(scan.root.path, scan.pattern, layout); + if (existsSync(candidate)) return candidate; + } + throw new Error("no Homebrew where the tool definition looks"); +} + +const scratch = realpathSync(mkdtempSync(join(tmpdir(), "lithe-lldb-test-"))); +try { + const root = join(scratch, "Lithe LLDB Demo"); + mkdirSync(root); + const source = join(root, "main.c"); + const line = 5; + writeFileSync(source, [ + "#include ", + "", + "int main(void) {", + " int answer = 42;", + ' printf("answer %d\\n", answer);', + " return 0;", + "}", + "", + ].join("\n")); + const program = join(root, "main"); + run("clang", ["-g", "-O0", source, "-o", program]); + + await check("the lldb-dap found on PATH or through xcrun debugs a program", async () => { + const lldbDap = systemLldbDap(); + console.log(` ${lldbDap}`); + await debugSession(lldbDap, program, source, line); + }); + + if (process.env.LITHE_TEST_INSTALL === "0") { + console.log("- skipped the lldb-dap install (LITHE_TEST_INSTALL=0)"); + } else { + let brew; + await check("Homebrew is found where the tool definition looks and answers the version probe", () => { + brew = findBrew(); + const output = run(brew, brewTool.version.arguments); + const match = output.match(new RegExp(brewTool.version.pattern)); + assert.ok(match, `no version in ${JSON.stringify(output)}`); + console.log(` ${brew} ${match[1]}`); + }); + + let installed; + await check(`the ${installer.id} installer puts ${installer.commands.join(", ")} where its directory probe says`, () => { + assert.ok(brew, "needs Homebrew"); + assert.deepEqual(Object.keys(installer.targets), ["toolDefault"]); + run(brew, installer.arguments, { timeout: installer.timeoutSeconds * 1000 }); + const [probe] = installer.targets.toolDefault.directory; + const prefix = run(brew, probe.arguments).trim(); + assert.ok(isAbsolute(prefix), `brew ${probe.arguments.join(" ")} printed ${JSON.stringify(prefix)}`); + const directory = join(prefix, probe.append ?? ""); + for (const command of installer.commands) { + const listing = existsSync(directory) ? readdirSync(directory).join(" ") : "(missing)"; + assert.ok(existsSync(join(directory, command)), `${command} in ${directory}, which holds: ${listing}`); + } + installed = join(directory, installer.commands[0]); + }); + + await check("the installed lldb-dap debugs a program", async () => { + assert.ok(installed, "needs the installed lldb-dap"); + console.log(` ${installed}`); + await debugSession(installed, program, source, line); + }); + } +} catch (error) { + failed = true; + console.error(error.stack); +} finally { + rmSync(scratch, { recursive: true, force: true }); +} +process.exitCode = failed ? 1 : 0;