├── Cargo.lock.license ├── Cargo.nix.license ├── .gitignore ├── .gitattributes ├── default.nix ├── .config └── nextest.toml ├── src ├── schema.sql ├── log.rs ├── main.rs ├── config.rs ├── db.rs ├── index.rs ├── substituter.rs ├── server.rs └── store.rs ├── shell.nix ├── tests ├── nixos-tests.nix ├── debugees.nix ├── nixos │ ├── main.nix │ └── fetchdrv.nix └── test.rs ├── nixseparatedebuginfod.nix ├── test.nix ├── .github └── workflows │ └── test.yml ├── flake.nix ├── Cargo.toml ├── flake.lock ├── Changelog.md ├── module.nix ├── LICENSES ├── CC0-1.0.txt └── GPL-3.0-only.txt └── README.md /Cargo.lock.license: -------------------------------------------------------------------------------- 1 | SPDX-FileCopyrightText: 2023 Guillaume Girol 2 | 3 | SPDX-License-Identifier: CC0-1.0 4 | -------------------------------------------------------------------------------- /Cargo.nix.license: -------------------------------------------------------------------------------- 1 | SPDX-FileCopyrightText: 2023 Guillaume Girol 2 | 3 | SPDX-License-Identifier: CC0-1.0 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Guillaume Girol 2 | # 3 | # SPDX-License-Identifier: CC0-1.0 4 | 5 | /target 6 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Guillaume Girol 2 | # 3 | # SPDX-License-Identifier: CC0-1.0 4 | 5 | Cargo.nix linguist-generated=true 6 | -------------------------------------------------------------------------------- /default.nix: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Guillaume Girol 2 | # 3 | # SPDX-License-Identifier: CC0-1.0 4 | 5 | with import {}; callPackage ./nixseparatedebuginfod.nix {} 6 | -------------------------------------------------------------------------------- /.config/nextest.toml: -------------------------------------------------------------------------------- 1 | [profile.default] 2 | # I know, it's saaaaaaad to write flaky tests 3 | retries=4 4 | 5 | [profile.ci] 6 | # Print out output for failing tests as soon as they fail, and also at the end 7 | # of the run (for easy scrollability). 8 | failure-output = "immediate-final" 9 | # Do not cancel the test run on the first failure. 10 | fail-fast = false 11 | 12 | -------------------------------------------------------------------------------- /src/schema.sql: -------------------------------------------------------------------------------- 1 | -- SPDX-FileCopyrightText: 2023 Guillaume Girol 2 | -- 3 | -- SPDX-License-Identifier: GPL-3.0-only 4 | 5 | create table if not exists builds ( 6 | buildid text unique not null, 7 | executable text, 8 | debuginfo text, 9 | source text 10 | ); 11 | 12 | create index if not exists bybuildid on builds(buildid); 13 | 14 | create table if not exists version (version int not null); 15 | 16 | create table if not exists gc (timestamp int not null); 17 | 18 | create table if not exists id (next int not null); 19 | -------------------------------------------------------------------------------- /shell.nix: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Guillaume Girol 2 | # 3 | # SPDX-License-Identifier: CC0-1.0 4 | 5 | { pkgs ? import {} }: 6 | with pkgs; 7 | mkShell { 8 | nativeBuildInputs = [ 9 | cargo 10 | rustc 11 | rustfmt 12 | clippy 13 | rust-analyzer 14 | sqlite 15 | openssl 16 | pkg-config 17 | reuse 18 | cargo-license 19 | cargo-outdated 20 | cargo-nextest 21 | elfutils.bin 22 | ] 23 | ++ lib.optionals (!gdb.meta.unsupported) [gdb]; 24 | buildInputs = [ libarchive ]; 25 | RUST_BACKTRACE="full"; 26 | } 27 | -------------------------------------------------------------------------------- /tests/nixos-tests.nix: -------------------------------------------------------------------------------- 1 | { pkgs ? (import (builtins.fetchTarball "channel:nixos-25.05") { }) }: 2 | let 3 | overlay = self: super: { 4 | nixseparatedebuginfod = super.callPackage ../nixseparatedebuginfod.nix { }; 5 | }; 6 | lib = pkgs.lib; 7 | nixos-lib = import (pkgs.path + "/nixos/lib") { }; 8 | testDir = ./nixos; 9 | mkTest = path: nixos-lib.runTest ({ hostPkgs = pkgs; } // ((import path) { inherit pkgs lib overlay; })); 10 | in 11 | lib.mapAttrs' 12 | (filename: _type: { 13 | name = lib.removeSuffix ".nix" filename; 14 | value = mkTest (testDir + ("/" + filename)); 15 | }) 16 | (builtins.readDir testDir) 17 | 18 | -------------------------------------------------------------------------------- /src/log.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: 2023 Guillaume Girol 2 | // 3 | // SPDX-License-Identifier: GPL-3.0-only 4 | 5 | //! Logging utilities 6 | 7 | use std::fmt::Display; 8 | 9 | /// Adds a way to log errors to [Result] 10 | pub trait ResultExt { 11 | /// if `self` is an error, then calls [tracing::warn!] with this error 12 | /// 13 | /// otherwise does nothing 14 | fn or_warn(self); 15 | } 16 | 17 | impl ResultExt for Result<(), T> { 18 | fn or_warn(self) { 19 | match self { 20 | Ok(()) => (), 21 | Err(e) => tracing::warn!("{:#}", e), 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /nixseparatedebuginfod.nix: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Guillaume Girol 2 | # 3 | # SPDX-License-Identifier: CC0-1.0 4 | 5 | { callPackage, libarchive, pkg-config, lib }: 6 | let 7 | customBuildRustCrateForPkgs = pkgs: pkgs.buildRustCrate.override { 8 | defaultCrateOverrides = pkgs.defaultCrateOverrides // { 9 | compress-tools = attrs: { 10 | buildInputs = [ libarchive ]; 11 | nativeBuildInputs = [ pkg-config ]; 12 | }; 13 | }; 14 | }; 15 | generatedBuild = callPackage ./Cargo.nix { 16 | buildRustCrateForPkgs = customBuildRustCrateForPkgs; 17 | }; 18 | in generatedBuild.rootCrate.build 19 | 20 | -------------------------------------------------------------------------------- /test.nix: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Guillaume Girol 2 | # 3 | # SPDX-License-Identifier: CC0-1.0 4 | 5 | let 6 | compiling_on_stable_and_unstable = map 7 | (channel: 8 | let 9 | pkgs = import (builtins.fetchTarball ("channel:" + channel)) { }; 10 | nixseparatedebuginfod = pkgs.callPackage ./nixseparatedebuginfod.nix { }; 11 | in 12 | nixseparatedebuginfod.overrideAttrs ({ name, ... }: { 13 | name = name + "-" + channel; 14 | }) 15 | ) [ "nixos-25.05" ]; 16 | nixos_tests = builtins.attrValues (import ./tests/nixos-tests.nix { }); 17 | in 18 | compiling_on_stable_and_unstable ++ nixos_tests 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /tests/debugees.nix: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Guillaume Girol 2 | # 3 | # SPDX-License-Identifier: GPL-3.0-only 4 | 5 | let 6 | nixpkgs = builtins.fetchTarball { 7 | url = "https://github.com/NixOS/nixpkgs/archive/087416863971.tar.gz"; 8 | sha256 = "sha256:0gw5l5bj3zcgxhp7ki1jafy6sl5nk4vr43hal94lhi15kg2vfmfy"; 9 | }; 10 | pkgs = import nixpkgs { }; 11 | in 12 | rec { 13 | inherit (pkgs) 14 | gnumake # has source in archive 15 | nix # has source in flat files 16 | nlohmann_json 17 | python3 18 | python310 19 | rpm; 20 | sl = pkgs.sl.overrideAttrs (_:{ separateDebugInfo = true; }); 21 | mailutils_drvhash1 = pkgs.mailutils; 22 | mailutils_drvhash2 = mailutils_drvhash1.overrideAttrs (old: { 23 | src = old.src.overrideAttrs(_: { yay=1; }); 24 | }); 25 | } 26 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: "Test" 2 | on: 3 | pull_request: 4 | push: 5 | # Make sure CI fails on all warnings, including Clippy lints 6 | env: 7 | RUSTFLAGS: "-Dwarnings" 8 | jobs: 9 | linux: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v2.5.0 13 | - name: Install Nix 14 | uses: nixbuild/nix-quick-install-action@v32 15 | - name: Set up Nix cache 16 | uses: nix-community/cache-nix-action@v6 17 | with: 18 | primary-key: nix-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('**/*.nix', '**/flake.lock') }} 19 | restore-prefixes-first-match: nix-${{ runner.os }}-${{ runner.arch }} 20 | - run: nix config show 21 | - run: nix-build test.nix 22 | - run: nix-shell -I nixpkgs=channel:nixos-25.05 --run "cargo clippy && cargo nextest run --profile ci" 23 | -------------------------------------------------------------------------------- /flake.nix: -------------------------------------------------------------------------------- 1 | { 2 | description = "Downloads and provides debug symbols and source code for nix derivations to gdb and other debuginfod-capable debuggers as needed."; 3 | 4 | inputs = { 5 | nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable"; 6 | flake-utils.url = "github:numtide/flake-utils"; 7 | }; 8 | 9 | outputs = { 10 | self, 11 | nixpkgs, 12 | flake-utils, 13 | ... 14 | }: 15 | let 16 | packagesWith = pkgs: { 17 | nixseparatedebuginfod = pkgs.callPackage ./nixseparatedebuginfod.nix {}; 18 | }; 19 | in 20 | flake-utils.lib.eachDefaultSystem (system: 21 | let 22 | pkgs = import nixpkgs { 23 | inherit system; 24 | overlays = [self.overlays.default]; 25 | }; 26 | in rec { 27 | packages = packagesWith pkgs // { 28 | default = packages.nixseparatedebuginfod; 29 | }; 30 | devShells.default = pkgs.callPackage ./shell.nix {}; 31 | } 32 | ) // { 33 | nixosModules.default = import ./module.nix; 34 | overlays.default = final: prev: packagesWith final; 35 | }; 36 | } 37 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Guillaume Girol 2 | # 3 | # SPDX-License-Identifier: GPL-3.0-only 4 | 5 | [package] 6 | name = "nixseparatedebuginfod" 7 | version = "0.4.1" 8 | edition = "2021" 9 | 10 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 11 | 12 | [profile.release] 13 | debug = true 14 | 15 | [dependencies] 16 | anyhow = "1.0.68" 17 | base16 = "0.2.1" 18 | compress-tools = { version = "0.15.0", features = [ "tokio_support" ] } 19 | directories = "5" 20 | futures-util = "0.3" 21 | object = "0.36" 22 | once_cell = "1.17.0" 23 | sqlx = { version = "0.8", features = [ "runtime-tokio", "sqlite" ] } 24 | tokio = { version = "1.24.1", features = ["process", "fs", "sync"] } 25 | tokio-util = { version = "0.7.4", features = ["io-util"] } 26 | walkdir = "2.3.2" 27 | sha2 = "0.10.6" 28 | axum = "0.7" 29 | axum-macros = "0.4" 30 | clap = { version = "4", features = [ "derive" ] } 31 | tower-http = { version = "0.5", features = [ "trace" ] } 32 | tracing = "0.1.37" 33 | tracing-subscriber = { version = "0.3.16", features = [ "env-filter" ] } 34 | http = "1" 35 | serde = { version = "1.0", features = ["derive"] } 36 | serde_json = "1" 37 | tempfile = "3" 38 | async-trait = "0.1" 39 | async-recursion = "1" 40 | reqwest = { version = "0.12.0", features = [ "stream" ] } 41 | pathrs = "0.1.3" 42 | 43 | [dev-dependencies] 44 | assert_cmd = "2" 45 | rand = "0.8" 46 | prctl = "1" 47 | maplit = "1" 48 | reqwest = { version = "0.12.0", features = [ "blocking" ] } 49 | -------------------------------------------------------------------------------- /flake.lock: -------------------------------------------------------------------------------- 1 | { 2 | "nodes": { 3 | "flake-utils": { 4 | "inputs": { 5 | "systems": "systems" 6 | }, 7 | "locked": { 8 | "lastModified": 1685518550, 9 | "narHash": "sha256-o2d0KcvaXzTrPRIo0kOLV0/QXHhDQ5DTi+OxcjO8xqY=", 10 | "owner": "numtide", 11 | "repo": "flake-utils", 12 | "rev": "a1720a10a6cfe8234c0e93907ffe81be440f4cef", 13 | "type": "github" 14 | }, 15 | "original": { 16 | "owner": "numtide", 17 | "repo": "flake-utils", 18 | "type": "github" 19 | } 20 | }, 21 | "nixpkgs": { 22 | "locked": { 23 | "lastModified": 1686277352, 24 | "narHash": "sha256-quryYLnntwZZrwJ4Vsx24hiCkwiYZAEttiOu983akGg=", 25 | "owner": "NixOS", 26 | "repo": "nixpkgs", 27 | "rev": "a9fa8f8450a2ae296f152a9b3d52df68d24b7cfc", 28 | "type": "github" 29 | }, 30 | "original": { 31 | "owner": "NixOS", 32 | "ref": "nixpkgs-unstable", 33 | "repo": "nixpkgs", 34 | "type": "github" 35 | } 36 | }, 37 | "root": { 38 | "inputs": { 39 | "flake-utils": "flake-utils", 40 | "nixpkgs": "nixpkgs" 41 | } 42 | }, 43 | "systems": { 44 | "locked": { 45 | "lastModified": 1681028828, 46 | "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", 47 | "owner": "nix-systems", 48 | "repo": "default", 49 | "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", 50 | "type": "github" 51 | }, 52 | "original": { 53 | "owner": "nix-systems", 54 | "repo": "default", 55 | "type": "github" 56 | } 57 | } 58 | }, 59 | "root": "root", 60 | "version": 7 61 | } 62 | -------------------------------------------------------------------------------- /Changelog.md: -------------------------------------------------------------------------------- 1 | 6 | 7 | # `v0.4.1` 8 | * fix CVE-2025-61557: Due to a path traversal issue, nixseparatedebuginfod < `0.4.1` would serve any file on the system it could read, even outside the nix store. When using the NixOS module, nixseparatedebuginfod runs as a systemd dynamic user and listens on localhost, which means that this bug only allows local users to read world-readable files, which is unlikely to be a problem. However different setups where nixseparatedebuginfod runs as a user with access to sensitive files and/or listens on the open network should upgrade. Please note that even with the fix, nixseparatedebuginfod will disclose the content of any file in the store to clients that request it. This is by design and is unlikely to ever change. 9 | 10 | # `v0.4.0` 11 | 12 | * fix ignoring `RUST_LOG` 13 | * fix fetching drv files from substituters 14 | * does not build anymore with the version of rustc shipped by NixOS 23.11 15 | 16 | # `v0.3.4` 17 | 18 | * fix crash on malformed ELF 19 | * fix parsing `extra-` options in nix configuration 20 | * module: fix using with nix 2.3 21 | * don't emit timestamps in logs (journald does it already) 22 | 23 | # `v0.3.3` 24 | 25 | * handle sources inlined from another derivation (for example C++ template instantiation). Related: nixpkgs PR 279455 26 | 27 | # `v0.3.2` 28 | 29 | * fix version number in v0.3.1 30 | 31 | # `v0.3.1` 32 | 33 | * don't crash on startup with nix 2.3 34 | 35 | # `v0.3.0` 36 | * handle better installs with non-trivial `allowed-users` nix option 37 | * systemd hardening 38 | 39 | # `v0.2.0` 40 | - switch to jemalloc for significantly decreased peak RSS during indexation 41 | - use nix-store --query --valid-derivers when possible 42 | - actually implement substituting `.drv` files 43 | - implement support for the same API as `dwarffs` (does not provide source) 44 | 45 | # v0.1.0 46 | - initial release 47 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: 2023 Guillaume Girol 2 | // 3 | // SPDX-License-Identifier: GPL-3.0-only 4 | 5 | #![warn(missing_docs)] 6 | 7 | //! A server implementing the debuginfod protocol for nix packages. 8 | //! 9 | //! A [db::Cache] stores the buildid -> (source, debuginfo, executable) mapping. 10 | //! 11 | //! A [index::StoreWatcher] waits for new store paths to appears, and walks them 12 | //! to populate the [db::Cache]. 13 | //! 14 | //! Finally the [server] module provides server that serves the populated [db::Cache]. 15 | 16 | use std::{net::SocketAddr, process::ExitCode}; 17 | 18 | use clap::Parser; 19 | 20 | use tracing_subscriber::{layer::SubscriberExt as _, util::SubscriberInitExt as _}; 21 | 22 | pub mod config; 23 | pub mod db; 24 | pub mod index; 25 | pub mod log; 26 | pub mod server; 27 | pub mod store; 28 | pub mod substituter; 29 | 30 | /// A debuginfod implementation that fetches debuginfo and sources from nix binary caches 31 | #[derive(Parser, Debug)] 32 | #[command(author, version, about, long_about = None)] 33 | pub struct Options { 34 | /// Address for the server 35 | #[arg(short, long, default_value = "127.0.0.1:1949")] 36 | listen_address: SocketAddr, 37 | /// Only index the store and quit without serving 38 | #[arg(short, long)] 39 | index_only: bool, 40 | } 41 | 42 | #[tokio::main] 43 | async fn main() -> anyhow::Result { 44 | if let (None, Some(dir)) = ( 45 | std::env::var_os("XDG_CACHE_HOME"), 46 | std::env::var_os("CACHE_DIRECTORY"), 47 | ) { 48 | // this env var is set by systemd 49 | std::env::set_var("XDG_CACHE_HOME", dir); 50 | } 51 | if std::env::var_os("RUST_LOG").is_none() { 52 | std::env::set_var( 53 | "RUST_LOG", 54 | "nixseparatedebuginfod=info,tower_http=debug,sqlx=warn,warn", 55 | ) 56 | } 57 | let args = Options::parse(); 58 | let fmt_layer = tracing_subscriber::fmt::layer().without_time(); 59 | tracing_subscriber::registry() 60 | .with(fmt_layer) 61 | .with(tracing_subscriber::EnvFilter::from_default_env()) 62 | .init(); 63 | 64 | // check that nix-store is present 65 | match store::detect_nix() { 66 | Err(e) => { 67 | tracing::error!("nix is not available: {:#}", e); 68 | return Ok(ExitCode::FAILURE); 69 | } 70 | Ok(()) => server::run_server(args).await, 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /tests/nixos/main.nix: -------------------------------------------------------------------------------- 1 | { pkgs, lib, overlay }: 2 | let 3 | secret-key = "key-name:/COlMSRbehSh6YSruJWjL+R0JXQUKuPEn96fIb+pLokEJUjcK/2Gv8Ai96D7JGay5gDeUTx5wdpPgNvum9YtwA=="; 4 | public-key = "key-name:BCVI3Cv9hr/AIveg+yRmsuYA3lE8ecHaT4Db7pvWLcA="; 5 | in 6 | { 7 | name = "nixseparatedebuginfod"; 8 | /* A binary cache with debug info and source for nix */ 9 | nodes.cache = { pkgs, ... }: { 10 | services.nix-serve = { 11 | enable = true; 12 | secretKeyFile = builtins.toFile "secret-key" secret-key; 13 | openFirewall = true; 14 | }; 15 | system.extraDependencies = [ 16 | pkgs.gnumake.debug 17 | pkgs.gnumake.src 18 | pkgs.gnumake 19 | pkgs.sl 20 | ]; 21 | }; 22 | /* the machine where we need the debuginfo */ 23 | nodes.machine = { 24 | services.nixseparatedebuginfod.enable = true; 25 | nixpkgs.overlays = [ overlay ]; 26 | nix.settings = { 27 | substituters = lib.mkForce [ "http://cache:5000" ]; 28 | trusted-public-keys = [ public-key ]; 29 | }; 30 | environment.systemPackages = [ 31 | pkgs.gnumake 32 | pkgs.valgrind 33 | pkgs.gdb 34 | (pkgs.writeShellScriptBin "wait_for_indexation" '' 35 | set -x 36 | while debuginfod-find debuginfo /run/current-system/sw/bin/make |& grep 'File too large'; do 37 | sleep 1; 38 | done 39 | '') 40 | ]; 41 | system.extraDependencies = [ 42 | pkgs.path 43 | ]; 44 | }; 45 | testScript = '' 46 | start_all() 47 | cache.wait_for_unit("nix-serve.service") 48 | cache.wait_for_open_port(5000) 49 | machine.wait_for_unit("nixseparatedebuginfod.service") 50 | machine.wait_for_open_port(1949) 51 | 52 | with subtest("show the config to debug the test"): 53 | machine.succeed("nix --extra-experimental-features nix-command show-config |& logger") 54 | machine.succeed("cat /etc/nix/nix.conf |& logger") 55 | with subtest("check that the binary cache works"): 56 | machine.succeed("nix-store -r ${pkgs.sl}") 57 | 58 | # nixseparatedebuginfod needs .drv to associate executable -> source 59 | # on regular systems this would be provided by nixos-rebuild 60 | machine.succeed("nix-instantiate ${pkgs.path} -A gnumake") 61 | 62 | machine.succeed("timeout 600 wait_for_indexation") 63 | 64 | # test debuginfod-find 65 | machine.succeed("debuginfod-find debuginfo /run/current-system/sw/bin/make") 66 | 67 | # test that gdb can fetch source 68 | out = machine.succeed("gdb /run/current-system/sw/bin/make --batch -x ${builtins.toFile "commands" '' 69 | start 70 | l 71 | ''}") 72 | print(out) 73 | assert 'main (int argc, char **argv, char **envp)' in out 74 | 75 | # test that valgrind can display location information 76 | # we ask valgrind to show leak kinds which are usually false positives, so taht we get a source file report. 77 | out = machine.succeed("valgrind --leak-check=full --show-leak-kinds=all make --version 2>&1") 78 | print(out) 79 | assert 'main.c' in out 80 | ''; 81 | } 82 | -------------------------------------------------------------------------------- /src/config.rs: -------------------------------------------------------------------------------- 1 | //! parsing nix.conf 2 | 3 | use anyhow::Context; 4 | use std::collections::{hash_map::Entry, HashMap}; 5 | 6 | /// A Key-value representation of nix.conf 7 | pub type NixConfig = HashMap; 8 | 9 | /// Parse the current nix config by running nix show-config 10 | /// 11 | /// Concatenates together the extra-* options 12 | pub async fn get_nix_config() -> anyhow::Result { 13 | let mut cmd = tokio::process::Command::new("nix"); 14 | cmd.args([ 15 | "--extra-experimental-features", 16 | "nix-command", 17 | "show-config", 18 | ]); 19 | let output = cmd.output().await.context("running nix show-config")?; 20 | anyhow::ensure!( 21 | output.status.success(), 22 | "nix show-config failed: {:?} {} {}", 23 | output.status, 24 | String::from_utf8_lossy(&output.stderr), 25 | String::from_utf8_lossy(&output.stdout) 26 | ); 27 | let out = String::from_utf8(output.stdout).context("nix show-config returned non utf8 data")?; 28 | parse_nix_config(&out) 29 | } 30 | 31 | fn parse_nix_config(text: &str) -> anyhow::Result { 32 | let mut extras = NixConfig::new(); 33 | let mut result = NixConfig::new(); 34 | for line in text.split('\n') { 35 | if let Some(cut) = line.find('=') { 36 | let key = &line[..cut].trim(); 37 | let value = &line[(cut + 1)..].trim(); 38 | let map = if key.starts_with("extra-") { 39 | &mut extras 40 | } else { 41 | &mut result 42 | }; 43 | match map.entry(key.to_string()) { 44 | Entry::Occupied(_) => { 45 | anyhow::bail!("several values for nix config entry {}", key) 46 | } 47 | Entry::Vacant(e) => e.insert(value.to_string()), 48 | }; 49 | } 50 | } 51 | for (key, value) in extras { 52 | result 53 | .entry(key[6..].to_string()) 54 | .and_modify(|before| { 55 | before.push(' '); 56 | before.push_str(&value); 57 | }) 58 | .or_insert_with(|| value); 59 | } 60 | Ok(result) 61 | } 62 | 63 | #[test] 64 | fn nix_config() { 65 | let config = r#" 66 | foo = bar 67 | # comment 68 | baz = complex"#; 69 | let expected = maplit::hashmap! { "foo".to_string() => "bar".to_string(), "baz".to_string() => "complex".to_string() }; 70 | assert_eq!(parse_nix_config(config).unwrap(), expected); 71 | } 72 | 73 | #[test] 74 | fn nix_config_extra_empty() { 75 | let config = r#"extra-experimental-features = nix-command"#; 76 | let expected = 77 | maplit::hashmap! { "experimental-features".to_string() => "nix-command".to_string() }; 78 | assert_eq!(parse_nix_config(config).unwrap(), expected); 79 | } 80 | 81 | #[test] 82 | fn nix_config_extra() { 83 | let config = r#" 84 | experimental-features = flakes 85 | extra-experimental-features = nix-command"#; 86 | let expected = maplit::hashmap! { "experimental-features".to_string() => "flakes nix-command".to_string() }; 87 | assert_eq!(parse_nix_config(config).unwrap(), expected); 88 | } 89 | 90 | #[test] 91 | fn nix_config_extra_before() { 92 | let config = r#" 93 | extra-experimental-features = nix-command 94 | experimental-features = flakes"#; 95 | let expected = maplit::hashmap! { "experimental-features".to_string() => "flakes nix-command".to_string() }; 96 | assert_eq!(parse_nix_config(config).unwrap(), expected); 97 | } 98 | -------------------------------------------------------------------------------- /tests/nixos/fetchdrv.nix: -------------------------------------------------------------------------------- 1 | { pkgs, lib, overlay }: 2 | let 3 | secret-key = "key-name:/COlMSRbehSh6YSruJWjL+R0JXQUKuPEn96fIb+pLokEJUjcK/2Gv8Ai96D7JGay5gDeUTx5wdpPgNvum9YtwA=="; 4 | public-key = "key-name:BCVI3Cv9hr/AIveg+yRmsuYA3lE8ecHaT4Db7pvWLcA="; 5 | in 6 | { 7 | name = "fetch-drv-from-cache"; 8 | /* A binary cache with debug info, derivation, and source for sl */ 9 | nodes.cache = { pkgs, ... }: { 10 | services.nix-serve = { 11 | enable = true; 12 | secretKeyFile = builtins.toFile "secret-key" secret-key; 13 | openFirewall = true; 14 | }; 15 | system.extraDependencies = [ 16 | pkgs.stdenv 17 | (lib.getDev pkgs.ncurses) 18 | (lib.getLib pkgs.ncurses) 19 | pkgs.sl.src 20 | pkgs.bash 21 | pkgs.path 22 | ]; 23 | }; 24 | /* the machine where we need the debuginfo */ 25 | nodes.machine = { 26 | virtualisation.useNixStoreImage = true; 27 | virtualisation.writableStore = true; 28 | 29 | services.nixseparatedebuginfod.enable = true; 30 | nixpkgs.overlays = [ overlay ]; 31 | nix.settings = { 32 | substituters = lib.mkForce [ "http://cache:5000" ]; 33 | trusted-public-keys = [ public-key ]; 34 | }; 35 | systemd.services.nixseparatedebuginfod.environment.RUST_LOG = "nixseparatedebuginfod=debug,sqlx=warn,tower=debug,info"; 36 | environment.systemPackages = [ 37 | pkgs.gdb 38 | (pkgs.writeShellScriptBin "wait_for_indexation" '' 39 | set -x 40 | while debuginfod-find debuginfo "$1"/bin/sl |& grep 'File too large'; do 41 | sleep 1; 42 | done 43 | echo "debuginfod-find stopped saying File too large" 44 | '') 45 | ]; 46 | system.extraDependencies = [ 47 | pkgs.path 48 | ]; 49 | }; 50 | testScript = /* python */ '' 51 | start_all() 52 | cache.wait_for_unit("nix-serve.service") 53 | cache.wait_for_open_port(5000) 54 | machine.wait_for_unit("nixseparatedebuginfod.service") 55 | machine.wait_for_open_port(1949) 56 | 57 | with subtest("show the config to debug the test"): 58 | machine.succeed("nix --extra-experimental-features nix-command show-config |& logger") 59 | machine.succeed("cat /etc/nix/nix.conf |& logger") 60 | machine.succeed("systemctl cat nixseparatedebuginfod.service |& logger") 61 | 62 | with subtest("populate the cache with sl and its drv file"): 63 | # it's important to build in the vm to avoid a situation where 64 | # the deriver inherited from the substituter is not the same as 65 | # the one evaluated from nixpkgs locally 66 | sl_path = cache.succeed("nix-build -E 'with import ${pkgs.path} {}; sl.overrideAttrs (_: { separateDebugInfo = true; })'").strip() 67 | print(f"sl has path {sl_path}") 68 | cache.succeed(f"nix-store --query --deriver {sl_path} |& logger --stderr |& grep /nix/store") 69 | 70 | with subtest("fetch sl, but not its drv file"): 71 | machine.succeed(f"nix-store --realise {sl_path}") 72 | 73 | machine.succeed(f"nix-store --query --deriver {sl_path}/bin/sl |& logger --stderr |& grep /nix/store") 74 | machine.succeed(f"[ ! -e $(nix-store --query --deriver {sl_path} ) ]") 75 | 76 | machine.succeed(f"timeout 600 wait_for_indexation {sl_path}") 77 | 78 | # obtaining debuginfo requires fetching the drv file from the cache 79 | machine.succeed(f"debuginfod-find debuginfo {sl_path}/bin/sl") 80 | 81 | # test that gdb can fetch source 82 | out = machine.succeed(f"gdb {sl_path}/bin/sl --batch -x ${builtins.toFile "commands" '' 83 | start 84 | l 85 | ''}") 86 | print(out) 87 | assert 'int main(' in out 88 | ''; 89 | } 90 | -------------------------------------------------------------------------------- /module.nix: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Guillaume Girol 2 | # 3 | # SPDX-License-Identifier: CC0-1.0 4 | 5 | { pkgs, lib, config, ... }: 6 | let 7 | cfg = config.services.nixseparatedebuginfod; 8 | url = "127.0.0.1:${toString cfg.port}"; 9 | maybeAdd = x: list: if builtins.elem x list then list else list ++ [ x ]; 10 | recentNix = lib.lists.findFirst 11 | (nix: nix != null && lib.versionAtLeast 12 | nix.version "2.18") 13 | config.nix.package [ 14 | config.nix.package 15 | pkgs.nix 16 | ((pkgs.nixVersions or { }).nix_2_18 or null) 17 | pkgs.nixUnstable 18 | ]; 19 | in 20 | { 21 | imports = [ 22 | (lib.mkRemovedOptionModule [ "services" "nixseparatedebuginfod" "allowUser" ] "this option is not necessary anymore") 23 | ]; 24 | 25 | options = { 26 | services.nixseparatedebuginfod = { 27 | enable = lib.mkEnableOption "separatedebuginfod, a debuginfod server providing source and debuginfo for nix packages"; 28 | port = lib.mkOption { 29 | description = "port to listen"; 30 | default = 1949; 31 | type = lib.types.port; 32 | }; 33 | }; 34 | }; 35 | config = lib.mkIf cfg.enable { 36 | systemd.services.nixseparatedebuginfod = { 37 | wantedBy = [ "multi-user.target" ]; 38 | wants = [ "nix-daemon.service" ]; 39 | after = [ "nix-daemon.service" ]; 40 | path = [ recentNix ]; 41 | serviceConfig = { 42 | ExecStart = [ "${pkgs.nixseparatedebuginfod}/bin/nixseparatedebuginfod -l ${url}" ]; 43 | Restart = "on-failure"; 44 | CacheDirectory = "nixseparatedebuginfod"; 45 | # nix does not like DynamicUsers in allowed-users 46 | User = "nixseparatedebuginfod"; 47 | Group = "nixseparatedebuginfod"; 48 | 49 | # hardening 50 | # Filesystem stuff 51 | ProtectSystem = "strict"; # Prevent writing to most of / 52 | ProtectHome = true; # Prevent accessing /home and /root 53 | PrivateTmp = true; # Give an own directory under /tmp 54 | PrivateDevices = true; # Deny access to most of /dev 55 | ProtectKernelTunables = true; # Protect some parts of /sys 56 | ProtectControlGroups = true; # Remount cgroups read-only 57 | RestrictSUIDSGID = true; # Prevent creating SETUID/SETGID files 58 | PrivateMounts = true; # Give an own mount namespace 59 | RemoveIPC = true; 60 | UMask = "0077"; 61 | 62 | # Capabilities 63 | CapabilityBoundingSet = ""; # Allow no capabilities at all 64 | NoNewPrivileges = true; # Disallow getting more capabilities. This is also implied by other options. 65 | 66 | # Kernel stuff 67 | ProtectKernelModules = true; # Prevent loading of kernel modules 68 | SystemCallArchitectures = "native"; # Usually no need to disable this 69 | ProtectKernelLogs = true; # Prevent access to kernel logs 70 | ProtectClock = true; # Prevent setting the RTC 71 | 72 | # Networking 73 | RestrictAddressFamilies = "AF_UNIX AF_INET AF_INET6"; 74 | 75 | # Misc 76 | LockPersonality = true; # Prevent change of the personality 77 | ProtectHostname = true; # Give an own UTS namespace 78 | RestrictRealtime = true; # Prevent switching to RT scheduling 79 | MemoryDenyWriteExecute = true; # Maybe disable this for interpreters like python 80 | RestrictNamespaces = true; 81 | }; 82 | }; 83 | 84 | users.users.nixseparatedebuginfod = { 85 | isSystemUser = true; 86 | group = "nixseparatedebuginfod"; 87 | }; 88 | 89 | users.groups.nixseparatedebuginfod = { }; 90 | 91 | # extra- settings were introduced in nix 2.4 92 | # sorry for those who use 2.3 93 | nix.settings = lib.optionalAttrs (lib.versionAtLeast config.nix.package.version "2.4") { 94 | extra-allowed-users = [ "nixseparatedebuginfod" ]; 95 | }; 96 | 97 | environment.variables.DEBUGINFOD_URLS = "http://${url}"; 98 | 99 | nixpkgs.overlays = [ 100 | (self: super: { 101 | nixseparatedebuginfod = super.callPackage ./nixseparatedebuginfod.nix { }; 102 | gdb-debuginfod = (super.gdb.override { enableDebuginfod = true; }).overrideAttrs (old: { 103 | configureFlags = maybeAdd "--with-system-gdbinit-dir=/etc/gdb/gdbinit.d" old.configureFlags; 104 | }); 105 | }) 106 | ]; 107 | 108 | environment.systemPackages = [ 109 | (lib.hiPrio pkgs.gdb-debuginfod) 110 | # valgrind support requires debuginfod-find on PATH 111 | (lib.hiPrio (lib.getBin (pkgs.elfutils.override { enableDebuginfod = true; }))) 112 | ]; 113 | 114 | environment.etc."gdb/gdbinit.d/nixseparatedebuginfod.gdb".text = "set debuginfod enabled on"; 115 | 116 | }; 117 | } 118 | -------------------------------------------------------------------------------- /LICENSES/CC0-1.0.txt: -------------------------------------------------------------------------------- 1 | Creative Commons Legal Code 2 | 3 | CC0 1.0 Universal 4 | 5 | CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE 6 | LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN 7 | ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS 8 | INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES 9 | REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS 10 | PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM 11 | THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED 12 | HEREUNDER. 13 | 14 | Statement of Purpose 15 | 16 | The laws of most jurisdictions throughout the world automatically confer 17 | exclusive Copyright and Related Rights (defined below) upon the creator 18 | and subsequent owner(s) (each and all, an "owner") of an original work of 19 | authorship and/or a database (each, a "Work"). 20 | 21 | Certain owners wish to permanently relinquish those rights to a Work for 22 | the purpose of contributing to a commons of creative, cultural and 23 | scientific works ("Commons") that the public can reliably and without fear 24 | of later claims of infringement build upon, modify, incorporate in other 25 | works, reuse and redistribute as freely as possible in any form whatsoever 26 | and for any purposes, including without limitation commercial purposes. 27 | These owners may contribute to the Commons to promote the ideal of a free 28 | culture and the further production of creative, cultural and scientific 29 | works, or to gain reputation or greater distribution for their Work in 30 | part through the use and efforts of others. 31 | 32 | For these and/or other purposes and motivations, and without any 33 | expectation of additional consideration or compensation, the person 34 | associating CC0 with a Work (the "Affirmer"), to the extent that he or she 35 | is an owner of Copyright and Related Rights in the Work, voluntarily 36 | elects to apply CC0 to the Work and publicly distribute the Work under its 37 | terms, with knowledge of his or her Copyright and Related Rights in the 38 | Work and the meaning and intended legal effect of CC0 on those rights. 39 | 40 | 1. Copyright and Related Rights. A Work made available under CC0 may be 41 | protected by copyright and related or neighboring rights ("Copyright and 42 | Related Rights"). Copyright and Related Rights include, but are not 43 | limited to, the following: 44 | 45 | i. the right to reproduce, adapt, distribute, perform, display, 46 | communicate, and translate a Work; 47 | ii. moral rights retained by the original author(s) and/or performer(s); 48 | iii. publicity and privacy rights pertaining to a person's image or 49 | likeness depicted in a Work; 50 | iv. rights protecting against unfair competition in regards to a Work, 51 | subject to the limitations in paragraph 4(a), below; 52 | v. rights protecting the extraction, dissemination, use and reuse of data 53 | in a Work; 54 | vi. database rights (such as those arising under Directive 96/9/EC of the 55 | European Parliament and of the Council of 11 March 1996 on the legal 56 | protection of databases, and under any national implementation 57 | thereof, including any amended or successor version of such 58 | directive); and 59 | vii. other similar, equivalent or corresponding rights throughout the 60 | world based on applicable law or treaty, and any national 61 | implementations thereof. 62 | 63 | 2. Waiver. To the greatest extent permitted by, but not in contravention 64 | of, applicable law, Affirmer hereby overtly, fully, permanently, 65 | irrevocably and unconditionally waives, abandons, and surrenders all of 66 | Affirmer's Copyright and Related Rights and associated claims and causes 67 | of action, whether now known or unknown (including existing as well as 68 | future claims and causes of action), in the Work (i) in all territories 69 | worldwide, (ii) for the maximum duration provided by applicable law or 70 | treaty (including future time extensions), (iii) in any current or future 71 | medium and for any number of copies, and (iv) for any purpose whatsoever, 72 | including without limitation commercial, advertising or promotional 73 | purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each 74 | member of the public at large and to the detriment of Affirmer's heirs and 75 | successors, fully intending that such Waiver shall not be subject to 76 | revocation, rescission, cancellation, termination, or any other legal or 77 | equitable action to disrupt the quiet enjoyment of the Work by the public 78 | as contemplated by Affirmer's express Statement of Purpose. 79 | 80 | 3. Public License Fallback. Should any part of the Waiver for any reason 81 | be judged legally invalid or ineffective under applicable law, then the 82 | Waiver shall be preserved to the maximum extent permitted taking into 83 | account Affirmer's express Statement of Purpose. In addition, to the 84 | extent the Waiver is so judged Affirmer hereby grants to each affected 85 | person a royalty-free, non transferable, non sublicensable, non exclusive, 86 | irrevocable and unconditional license to exercise Affirmer's Copyright and 87 | Related Rights in the Work (i) in all territories worldwide, (ii) for the 88 | maximum duration provided by applicable law or treaty (including future 89 | time extensions), (iii) in any current or future medium and for any number 90 | of copies, and (iv) for any purpose whatsoever, including without 91 | limitation commercial, advertising or promotional purposes (the 92 | "License"). The License shall be deemed effective as of the date CC0 was 93 | applied by Affirmer to the Work. Should any part of the License for any 94 | reason be judged legally invalid or ineffective under applicable law, such 95 | partial invalidity or ineffectiveness shall not invalidate the remainder 96 | of the License, and in such case Affirmer hereby affirms that he or she 97 | will not (i) exercise any of his or her remaining Copyright and Related 98 | Rights in the Work or (ii) assert any associated claims and causes of 99 | action with respect to the Work, in either case contrary to Affirmer's 100 | express Statement of Purpose. 101 | 102 | 4. Limitations and Disclaimers. 103 | 104 | a. No trademark or patent rights held by Affirmer are waived, abandoned, 105 | surrendered, licensed or otherwise affected by this document. 106 | b. Affirmer offers the Work as-is and makes no representations or 107 | warranties of any kind concerning the Work, express, implied, 108 | statutory or otherwise, including without limitation warranties of 109 | title, merchantability, fitness for a particular purpose, non 110 | infringement, or the absence of latent or other defects, accuracy, or 111 | the present or absence of errors, whether or not discoverable, all to 112 | the greatest extent permissible under applicable law. 113 | c. Affirmer disclaims responsibility for clearing rights of other persons 114 | that may apply to the Work or any use thereof, including without 115 | limitation any person's Copyright and Related Rights in the Work. 116 | Further, Affirmer disclaims responsibility for obtaining any necessary 117 | consents, permissions or other rights required for any use of the 118 | Work. 119 | d. Affirmer understands and acknowledges that Creative Commons is not a 120 | party to this document and has no duty or obligation with respect to 121 | this CC0 or use of the Work. 122 | -------------------------------------------------------------------------------- /src/db.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: 2023 Guillaume Girol 2 | // 3 | // SPDX-License-Identifier: GPL-3.0-only 4 | 5 | //! Cache for buildid -> debuginfo as a sqlite database 6 | 7 | use std::{str::FromStr, time::Duration}; 8 | 9 | use anyhow::{bail, Context}; 10 | use directories::ProjectDirs; 11 | use sha2::Digest; 12 | use sqlx::{ 13 | sqlite::{SqliteConnectOptions, SqlitePool}, 14 | Row, 15 | }; 16 | 17 | use crate::log::ResultExt; 18 | 19 | /// id of the row of a store path in `/nix/var/nix/db/db.sqlite` 20 | pub type Id = u32; 21 | 22 | /// An entry stored in the cache. 23 | /// 24 | /// `executable` is the full path to the executable of this buildid (executable includes .so). 25 | /// `debuginfo` is the full path to an elf object containing debuginfo. 26 | /// `source` is the store path of the source, either directory or archive. 27 | #[derive(Debug, Clone)] 28 | pub struct Entry { 29 | /// elf buildid, in base64 as printed by readelf 30 | pub buildid: String, 31 | /// store path of the stripped elf file 32 | pub executable: Option, 33 | /// store path of the separate debug info 34 | pub debuginfo: Option, 35 | /// store path of the source 36 | pub source: Option, 37 | } 38 | 39 | /// A cache storing the executable, debuginfo and source location for each buildid. 40 | /// 41 | /// Cloning this cache returns a new [Cache] object referring the same sqlite db. 42 | #[derive(Clone)] 43 | pub struct Cache { 44 | /// A connection to a backing sqlite db. 45 | sqlite: SqlitePool, 46 | } 47 | /// The schema of the sqlite db backing [Cache]. 48 | const SCHEMA: &str = include_str!("./schema.sql"); 49 | 50 | fn get_schema_version() -> u32 { 51 | let mut hasher = sha2::Sha256::new(); 52 | hasher.update(SCHEMA.as_bytes()); 53 | let hash = hasher.finalize(); 54 | u32::from_le_bytes(hash[0..4].try_into().unwrap()) 55 | } 56 | 57 | /// Checks whether this db has the right schema version 58 | async fn pool_is_valid(pool: &SqlitePool) -> anyhow::Result<()> { 59 | let row = sqlx::query("select version from version") 60 | .fetch_one(pool) 61 | .await 62 | .context("reading schema version")?; 63 | let version: u32 = row 64 | .try_get("version") 65 | .context("reading schema version first row")?; 66 | if version != get_schema_version() { 67 | bail!("incompatible cache version {}", version); 68 | } 69 | Ok(()) 70 | } 71 | 72 | /// Sets the schema on a empty db, and populate single row tables. 73 | async fn populate_pool(pool: &SqlitePool) -> anyhow::Result<()> { 74 | let mut transaction = pool 75 | .begin() 76 | .await 77 | .context("opening transaction to set schema on cache db")?; 78 | sqlx::query(SCHEMA) 79 | .execute(&mut *transaction) 80 | .await 81 | .context("setting schema on cache db")?; 82 | sqlx::query("insert into version values ($1);") 83 | .bind(get_schema_version()) 84 | .execute(&mut *transaction) 85 | .await 86 | .context("setting schema version on cache db")?; 87 | sqlx::query("insert into gc values (0);") 88 | .execute(&mut *transaction) 89 | .await 90 | .context("setting schema default timestamps on cache db")?; 91 | sqlx::query("insert into id values (0);") 92 | .execute(&mut *transaction) 93 | .await 94 | .context("setting schema default next id on cache db")?; 95 | transaction.commit().await?; 96 | Ok(()) 97 | } 98 | 99 | impl Cache { 100 | async fn connect_pool(url: &str) -> sqlx::Result { 101 | let opts = SqliteConnectOptions::from_str(url)?.busy_timeout(Duration::from_secs(60)); 102 | SqlitePool::connect_with(opts).await 103 | } 104 | 105 | /// Attempts to open the cache from disk. Does not try very hard. 106 | async fn open_weak() -> anyhow::Result { 107 | let dirs = ProjectDirs::from("eu", "xlumurb", "nixseparatedebuginfod"); 108 | let dirs = match dirs { 109 | Some(d) => d, 110 | None => bail!("could not determine cache dir in $HOME"), 111 | }; 112 | let mut path = dirs.cache_dir().to_owned(); 113 | std::fs::create_dir_all(&path) 114 | .with_context(|| format!("creating cache directory {}", path.display()))?; 115 | path.push("cache.sqlite3"); 116 | let cache_exists = path.exists(); 117 | let path_utf8 = match path.to_str() { 118 | Some(p) => p, 119 | None => bail!("cache path {} is not utf8", path.display()), 120 | }; 121 | let url = format!("file:{}?mode=rwc", path_utf8); 122 | let pool = Self::connect_pool(&url) 123 | .await 124 | .with_context(|| format!("failed to connect to {} with sqlite3", &url))?; 125 | if !cache_exists { 126 | populate_pool(&pool) 127 | .await 128 | .context("populating newly created cache") 129 | .or_warn(); 130 | }; 131 | let pool = match pool_is_valid(&pool).await { 132 | Ok(()) => pool, 133 | Err(e) => { 134 | tracing::warn!("cache {} is invalid, wiping it. {:#}", path.display(), e); 135 | pool.close().await; 136 | std::fs::remove_file(&path).unwrap_or_else(|e| { 137 | tracing::warn!("error removing corrupted cache {}: {:#}", path.display(), e) 138 | }); 139 | let pool = Self::connect_pool(&url) 140 | .await 141 | .with_context(|| format!("failed to connect to {} with sqlite3", &url))?; 142 | populate_pool(&pool) 143 | .await 144 | .context("populating empty cache")?; 145 | pool 146 | } 147 | }; 148 | Ok(Cache { sqlite: pool }) 149 | } 150 | 151 | /// Opens a cache, either from disk, or it it fails, in memory. 152 | pub async fn open() -> anyhow::Result { 153 | match Cache::open_weak().await { 154 | Err(e) => { 155 | tracing::warn!( 156 | "could not use on disk cache ({:#}), running cache in memory", 157 | e 158 | ); 159 | let pool = Self::connect_pool(":memory:") 160 | .await 161 | .context("opening in memory sql db")?; 162 | populate_pool(&pool) 163 | .await 164 | .context("populating empty cache")?; 165 | Ok(Cache { sqlite: pool }) 166 | } 167 | Ok(cache) => Ok(cache), 168 | } 169 | } 170 | 171 | /// Get the path of an elf object containing debuginfo for this buildid. 172 | /// 173 | /// The path may have been gc-ed, you are responsible to ensure it exists. 174 | pub async fn get_debuginfo(&self, buildid: &str) -> anyhow::Result> { 175 | let row = sqlx::query("select debuginfo from builds where buildid = $1;") 176 | .bind(buildid) 177 | .fetch_optional(&self.sqlite) 178 | .await 179 | .context("reading debuginfo from cache db")?; 180 | Ok(match row { 181 | None => None, 182 | Some(r) => r.try_get("debuginfo")?, 183 | }) 184 | } 185 | 186 | /// Get the path of an elf object containing text for this buildid. 187 | /// 188 | /// The path may have been gc-ed, you are responsible to ensure it exists. 189 | pub async fn get_executable(&self, buildid: &str) -> anyhow::Result> { 190 | let row = sqlx::query("select executable from builds where buildid = $1;") 191 | .bind(buildid) 192 | .fetch_optional(&self.sqlite) 193 | .await 194 | .context("reading executable from cache db")?; 195 | Ok(match row { 196 | None => None, 197 | Some(r) => r.try_get("executable")?, 198 | }) 199 | } 200 | 201 | /// Get the store path where the source of this buildid is. 202 | /// 203 | /// The path may have been gc-ed, you are responsible to ensure it exists. 204 | pub async fn get_source(&self, buildid: &str) -> anyhow::Result> { 205 | let row = sqlx::query("select source from builds where buildid = $1;") 206 | .bind(buildid) 207 | .fetch_optional(&self.sqlite) 208 | .await 209 | .context("reading executable from cache db")?; 210 | Ok(match row { 211 | None => None, 212 | Some(r) => r.try_get("source")?, 213 | }) 214 | } 215 | 216 | /// Register information for a buildid 217 | /// 218 | /// Only one of the each entry fields is stored for each buildid, if register is called several times 219 | /// for a single buildid, only the latest `Some` provided one is retained. 220 | pub async fn register(&self, entries: &[Entry]) -> anyhow::Result<()> { 221 | if entries.is_empty() { 222 | return Ok(()); 223 | } 224 | let mut transaction = self.sqlite.begin().await.context("transaction sqlite")?; 225 | for entry in entries { 226 | sqlx::query( 227 | "insert into builds 228 | values ($1, $2, $3, $4) 229 | on conflict(buildid) do update set 230 | executable = coalesce(excluded.executable, executable), 231 | debuginfo = coalesce(excluded.debuginfo, debuginfo), 232 | source = coalesce(excluded.source, source) 233 | ;", 234 | ) 235 | .bind(&entry.buildid) 236 | .bind(&entry.executable) 237 | .bind(&entry.debuginfo) 238 | .bind(&entry.source) 239 | .execute(&mut *transaction) 240 | .await 241 | .context("inserting build")?; 242 | } 243 | transaction 244 | .commit() 245 | .await 246 | .context("committing entry insert")?; 247 | Ok(()) 248 | } 249 | 250 | /// Store the next store path id to read from the nix db 251 | pub async fn set_next_id(&self, id: Id) -> anyhow::Result<()> { 252 | sqlx::query("update id set next = max(next, $1);") 253 | .bind(id) 254 | .execute(&self.sqlite) 255 | .await 256 | .context("advancing next registered id in cache db")?; 257 | Ok(()) 258 | } 259 | 260 | /// get the next store path id to read from the nix db 261 | pub async fn get_next_id(&self) -> anyhow::Result { 262 | let row = sqlx::query("select next from id") 263 | .fetch_one(&self.sqlite) 264 | .await 265 | .context("reading next registered id in cache db")?; 266 | row.try_get("next") 267 | .context("parsing next registered id from cache db") 268 | } 269 | } 270 | -------------------------------------------------------------------------------- /src/index.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: 2023 Guillaume Girol 2 | // 3 | // SPDX-License-Identifier: GPL-3.0-only 4 | 5 | //! Utilities to scan new store paths for buildids as they appear and populate the cache with them 6 | 7 | use crate::db::{Cache, Entry, Id}; 8 | use crate::log::ResultExt; 9 | use crate::store::{get_store_path, index_store_path}; 10 | use anyhow::Context; 11 | use futures_util::{future::join_all, stream::FuturesOrdered, FutureExt, StreamExt}; 12 | use sqlx::sqlite::SqliteConnectOptions; 13 | use sqlx::{ConnectOptions, Connection, Row}; 14 | use std::path::{Path, PathBuf}; 15 | use std::sync::Arc; 16 | use std::time::Duration; 17 | use tokio::sync::Mutex; 18 | use tokio::sync::{mpsc::Sender, Semaphore}; 19 | use tokio::task::JoinHandle; 20 | 21 | /// enqueue indexing of this many store paths at the same time 22 | const BATCH_SIZE: usize = 100; 23 | /// index at most thie many store paths at the same time 24 | const N_WORKERS: usize = 8; 25 | 26 | #[derive(Clone)] 27 | /// A helper to examine all new store paths in parallel. 28 | /// 29 | /// Cloning this structure returns a structure referring to the same internal state. 30 | pub struct StoreWatcher { 31 | cache: Cache, 32 | /// semaphore to prevent indexing too many store path at the same time 33 | /// 34 | /// this prevents too many open file errors 35 | semaphore: Arc, 36 | /// Locked when self.index_new_paths is running. 37 | working: Arc>, 38 | } 39 | 40 | impl StoreWatcher { 41 | /// Creates a [`StoreWatcher`] that populates the specified cache. 42 | /// 43 | /// To start it call [StoreWatcher::watch_store]. 44 | pub fn new(cache: Cache) -> Self { 45 | Self { 46 | cache, 47 | semaphore: Arc::new(Semaphore::new(N_WORKERS)), 48 | working: Arc::new(Mutex::new(())), 49 | } 50 | } 51 | 52 | /// Index new store paths if there are new store paths. 53 | /// 54 | /// If there are none, returns Ok(None). 55 | /// If there are some, starts a future to index them, and returns a JoinHandle to 56 | /// optionnally wait for completion of the indexation. 57 | pub async fn maybe_index_new_paths(&self) -> anyhow::Result>> { 58 | let start = self 59 | .cache 60 | .get_next_id() 61 | .await 62 | .context("reading cache next id")?; 63 | let (paths, end) = get_new_store_path_batch(start) 64 | .await 65 | .context("looking for new paths registered in the nix store")?; 66 | if paths.is_empty() { 67 | Ok(None) 68 | } else { 69 | let cloned_self = self.clone(); 70 | Ok(Some(tokio::spawn(async move { 71 | let guard = cloned_self.working.lock().await; 72 | // it's possible that we had to wait a lot for this lock and that more indexation 73 | // was done in between. 74 | match cloned_self.cache.get_next_id().await { 75 | Err(e) => tracing::warn!( 76 | "reading next id from sqlite db: {:#}, dropping indexation request", 77 | e 78 | ), 79 | Ok(new_start) => { 80 | if new_start == start { 81 | cloned_self.index_new_paths(paths, end).await; 82 | } else { 83 | // indexation was already in progress when we started waiting for the 84 | // lock. Now that we got the lock, indexation is complete and there is 85 | // nothing to do. 86 | tracing::info!("indexation already complete"); 87 | } 88 | } 89 | } 90 | drop(guard); 91 | }))) 92 | } 93 | } 94 | 95 | /// Indexes a single store path, and sends found buildids to this sender 96 | async fn index_store_path(&self, path: PathBuf, sendto: Sender) { 97 | let path2 = path.clone(); 98 | let permit = self 99 | .semaphore 100 | .clone() 101 | .acquire_owned() 102 | .await 103 | .expect("closed semaphore"); 104 | tokio::task::spawn_blocking(move || { 105 | index_store_path(path.as_path(), sendto, true); 106 | drop(permit); 107 | }) 108 | .await 109 | .with_context(|| format!("examining {} failed", path2.as_path().display())) 110 | .or_warn(); 111 | } 112 | 113 | /// Indexes all new store paths in the store by batches. 114 | /// 115 | /// Arguments are the first batch, as returned by [get_new_store_path_batch] 116 | async fn index_new_paths(&self, paths: Vec, id: Id) { 117 | if paths.is_empty() { 118 | return; 119 | }; 120 | tracing::info!("Starting indexation of new store paths"); 121 | let start = self.cache.get_next_id().await.unwrap_or(0); 122 | if start >= id { 123 | tracing::error!( 124 | size = paths.len(), 125 | end = id, 126 | start = start, 127 | "impossible batch" 128 | ); 129 | return; 130 | } 131 | tracing::debug!(size = paths.len(), end = id, start = start, "First batch"); 132 | let (entries_tx, mut entries_rx) = tokio::sync::mpsc::channel(3 * BATCH_SIZE); 133 | let batch: Vec<_> = paths 134 | .into_iter() 135 | .map(|path| self.index_store_path(path, entries_tx.clone())) 136 | .collect(); 137 | let batch_handle = join_all(batch).map(move |_| id).boxed(); 138 | let mut max_id = id; 139 | let mut unfinished_batches = FuturesOrdered::new(); 140 | unfinished_batches.push_back(batch_handle); 141 | let mut entry_buffer = Vec::with_capacity(BATCH_SIZE); 142 | let mut entries_tx_to_schedule_new_batches = Some(entries_tx); 143 | let mut just_wait_for_entries = false; 144 | loop { 145 | tokio::select! { 146 | entry = entries_rx.recv() => { 147 | match entry { 148 | Some(entry) => { 149 | entry_buffer.push(entry); 150 | if entry_buffer.len() >= BATCH_SIZE { 151 | match self.cache.register(&entry_buffer).await { 152 | Ok(()) => entry_buffer.clear(), 153 | Err(e) => tracing::warn!("cannot write entries to sqlite db: {:#}", e), 154 | } 155 | } 156 | }, 157 | None => { 158 | // no more entries to be recorded 159 | self.cache.register(&entry_buffer).await.context("registering entries").or_warn(); 160 | entry_buffer.clear(); 161 | tracing::info!("Done indexing new store paths"); 162 | return; 163 | } 164 | } 165 | } 166 | id = unfinished_batches.next(), if !just_wait_for_entries => { 167 | match id { 168 | Some(id) => { 169 | match self.cache.register(&entry_buffer).await { 170 | Ok(()) => { 171 | entry_buffer.clear(); 172 | self.cache.set_next_id(id).await.context("writing next id").or_warn(); 173 | tracing::debug!("batch {} complete", id); 174 | }, 175 | Err(e) => tracing::warn!("cannot write entries to sqlite db: {:#}", e), 176 | } 177 | }, 178 | None => { 179 | tracing::debug!("all batches examined, waiting for in-flight entries to be recorded"); 180 | just_wait_for_entries = true; 181 | }, 182 | } 183 | } 184 | } 185 | match entries_tx_to_schedule_new_batches { 186 | Some(ref entries_tx) if self.semaphore.available_permits() > 0 => { 187 | tracing::debug!("considering starting a new batch of store paths to index"); 188 | let (paths, id) = match get_new_store_path_batch(max_id).await { 189 | Ok(x) => x, 190 | Err(e) => { 191 | tracing::warn!("cannot read nix store db: {:#}", e); 192 | continue; 193 | } 194 | }; 195 | let batch: Vec<_> = paths 196 | .into_iter() 197 | .map(|path| self.index_store_path(path, entries_tx.clone())) 198 | .collect(); 199 | if batch.is_empty() { 200 | tracing::debug!("batch is empty"); 201 | // drops entries_tx which allows the function to return 202 | entries_tx_to_schedule_new_batches = None; 203 | } else { 204 | tracing::debug!( 205 | size = batch.len(), 206 | start = max_id, 207 | end = id, 208 | "Indexing new batch of paths" 209 | ); 210 | let batch_handle = join_all(batch).map(move |_| id).boxed(); 211 | max_id = id; 212 | unfinished_batches.push_back(batch_handle); 213 | } 214 | } 215 | _ => {} 216 | } 217 | } 218 | } 219 | 220 | /// starts a task that periodically indexes new store paths in the store. 221 | /// 222 | /// Returns immediately. 223 | pub fn watch_store(&self) { 224 | let self_clone = self.clone(); 225 | tokio::spawn(async move { 226 | loop { 227 | match self_clone.maybe_index_new_paths().await { 228 | Ok(None) => tokio::time::sleep(Duration::from_secs(60)).await, 229 | Ok(Some(handle)) => { 230 | handle.await.context("waiting for indexation").or_warn(); 231 | tokio::time::sleep(Duration::from_secs(60)).await; 232 | } 233 | Err(e) => { 234 | tracing::warn!("while watching store for new paths: {:#}", e); 235 | tokio::time::sleep(Duration::from_secs(1)).await; 236 | } 237 | } 238 | } 239 | }); 240 | } 241 | } 242 | 243 | /// Reads the nix db to find new store paths. 244 | /// 245 | /// New store paths are paths of id greater or equal to `from_id`. 246 | /// 247 | /// Returns the id you should call this function with for the "next" paths. 248 | async fn get_new_store_path_batch(from_id: Id) -> anyhow::Result<(Vec, Id)> { 249 | // note: this is a hack. One cannot open a sqlite db read only with WAL if the underlying 250 | // file is not writable. So we promise sqlite that the db will not be modified with 251 | // immutable=1, but it's false. 252 | let mut db = SqliteConnectOptions::new() 253 | .filename("/nix/var/nix/db/db.sqlite") 254 | .immutable(true) 255 | .read_only(true) 256 | .connect() 257 | .await 258 | .context("opening nix db")?; 259 | let rows = 260 | sqlx::query("select path, id from ValidPaths where id >= $1 order by id asc limit $2") 261 | .bind(from_id) 262 | .bind(BATCH_SIZE as u32) 263 | .fetch_all(&mut db) 264 | .await 265 | .context("reading nix db")?; 266 | let mut paths = Vec::new(); 267 | let mut max_id = 0; 268 | for row in rows { 269 | let path: &str = row.try_get("path").context("parsing path in nix db")?; 270 | let path = match get_store_path(Path::new(path)) { 271 | Some(path) => path, 272 | None => anyhow::bail!( 273 | "read corrupted stuff from nix db: {}, concurrent write?", 274 | path 275 | ), 276 | }; 277 | paths.push(PathBuf::from(path)); 278 | let id: Id = row.try_get("id").context("parsing id in nix db")?; 279 | max_id = id.max(max_id); 280 | } 281 | // As we lie about the database being immutable let's not keep the connection open 282 | db.close().await.context("closing nix db").or_warn(); 283 | if (max_id == 0) ^ paths.is_empty() { 284 | anyhow::bail!("read paths with id == 0..."); 285 | } 286 | Ok((paths, max_id + 1)) 287 | } 288 | 289 | /// Index this path, but harder than automatic indexation 290 | /// 291 | /// Specifically, this is allowed to download the .drv file from a cache. 292 | pub async fn index_single_store_path_to_cache( 293 | cache: &Cache, 294 | path: &Path, 295 | online: bool, 296 | ) -> anyhow::Result<()> { 297 | let (tx, mut rx) = tokio::sync::mpsc::channel(BATCH_SIZE); 298 | let path = path.to_path_buf(); 299 | let handle = tokio::task::spawn_blocking(move || index_store_path(&path, tx, !online)); 300 | let mut batch = Vec::new(); 301 | while let Some(entry) = rx.recv().await { 302 | batch.push(entry); 303 | if batch.len() > BATCH_SIZE { 304 | cache 305 | .register(&batch) 306 | .await 307 | .context("registering new entries")?; 308 | batch.clear(); 309 | } 310 | } 311 | cache 312 | .register(&batch) 313 | .await 314 | .context("registering new entries")?; 315 | handle.await?; 316 | Ok(()) 317 | } 318 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 6 | 7 | # `nixseparatedebuginfod` 8 | 9 | Downloads and provides debug symbols and source code for nix derivations to `gdb` and other `debuginfod`-capable debuggers as needed. 10 | 11 | ## Overview 12 | 13 | Most software in `nixpkgs` is stripped, so hard to debug. But some key packages are built with `separateDebugInfo = true`: debug symbols are put in a separate output `debug` which is not downloaded by default (and that's for the best, debug symbols can be huge). But when you do need the debug symbols, for example for `gdb`, you need to download this `debug` output and point `gdb` to it. This can be done manually, but is quite cumbersome. `nixseparatedebuginfod` does that for you on the fly, for separate debug outputs and even for the source! 14 | 15 | ## Setup 16 | 17 | [![Packaging status](https://repology.org/badge/vertical-allrepos/nixseparatedebuginfod.svg)](https://repology.org/project/nixseparatedebuginfod/versions) 18 | 19 | ### On NixOS 20 | 21 | A NixOS module is provided for your convenience: 22 | - directly upstream in NixOS ≥ 24.05 23 | - in `./module.nix` in this repo for older versions of NixOS. 24 | 25 | The module provides the following main option: 26 | ```nix 27 | services.nixseparatedebuginfod.enable = true; 28 | ``` 29 | 30 | On NixOS < 23.05, this option installs a version of `gdb` compiled with `debuginfod` support, so you should uninstall `gdb` from other sources (`nix-env`, `home-manager`). 31 | As the module sets an environment variable, you need to log out/log in again or reboot for it to work. 32 | 33 | #### NixOS ≥ 24.05 34 | 35 | Modify `/etc/nixos/configuration.nix` as follows: 36 | 37 | ```nix 38 | {config, pkgs, lib, ...}: { 39 | config = { 40 | /* 41 | ... existing options ... 42 | */ 43 | services.nixseparatedebuginfod.enable = true; 44 | }; 45 | } 46 | ``` 47 | 48 | #### Pure stable nix, NixOS < 24.05 49 | 50 | Add the module to the `imports` section of `/etc/nixos/configuration.nix`: 51 | ```nix 52 | {config, pkgs, lib, ...}: { 53 | imports = [ 54 | ((builtins.fetchTarball { 55 | url = "https://github.com/symphorien/nixseparatedebuginfod/archive/9b7a087a98095c26d1ad42a05102e0edfeb49b59.tar.gz"; 56 | sha256 = "sha256:1jbkv9mg11bcx3gg13m9d1jmg4vim7prny7bqsvlx9f78142qrlw"; 57 | }) + "/module.nix") 58 | ]; 59 | config = { 60 | services.nixseparatedebuginfod.enable = true; 61 | }; 62 | } 63 | ``` 64 | (adapt the revision and sha256 to a recent one). 65 | 66 | #### With [niv](https://github.com/nmattia/niv); NixOS < 24.05 67 | 68 | Run `niv add github symphorien/nixseparatedebuginfod` and add to the `imports` section of `/etc/nixos/configuration.nix`: 69 | ```nix 70 | {config, pkgs, lib, ...}: { 71 | imports = [ 72 | ((import nix/sources.nix {}).nixseparatedebuginfod + "/module.nix") 73 | ]; 74 | config = { 75 | services.nixseparatedebuginfod.enable = true; 76 | }; 77 | } 78 | ``` 79 | 80 | #### With flakes; NixOS < 24.05 81 | 82 | If you use flakes, modify your `/etc/nixos/flake.nix` as in this example: 83 | 84 | ```nix 85 | { 86 | inputs = { 87 | # ... 88 | nixseparatedebuginfod.url = "github:symphorien/nixseparatedebuginfod"; 89 | }; 90 | outputs = { 91 | nixpkgs, 92 | # ... 93 | nixseparatedebuginfod 94 | }: { 95 | nixosConfigurations.XXXXX = nixpkgs.lib.nixosSystem { 96 | system = "x86_64-linux"; 97 | modules = [ 98 | # ... 99 | nixseparatedebuginfod.nixosModules.default 100 | ]; 101 | config = { 102 | services.nixseparatedebuginfod.enable = true; 103 | }; 104 | }; 105 | }; 106 | } 107 | ``` 108 | 109 | ### Manual installation without the module 110 | 111 | If you cannot use the provided NixOS module, here are steps to set up `nixseparatedebuginfod` manually. 112 | 113 | - Compile `nixseparatedebuginfod` 114 | - `nix-build ./default.nix`, or 115 | - `cargo build --release`, inside the provided `nix-shell` (which provides `libarchive` and `pkg-config`). 116 | - Run `nixseparatedebuginfod`. 117 | - Set the environment variable `DEBUGINFOD_URLS` to `http://127.0.0.1:1949` 118 | 119 | Most software with `debuginfod` support should now use `nixseparatedebuginfod`. Some software needs to be configured further: 120 | 121 | #### `gdb` 122 | - In `~/.gdbinit` put 123 | ``` 124 | set debuginfod enabled on 125 | ``` 126 | otherwise, it will ask for confirmation every time. 127 | - With `nixpkgs` 22.11 or earlier, `gdb` is not compiled with `debuginfod` support in `nixpkgs` by default. To install a suitable version of `gdb`, replace the `pkgs.gdb` entry in `home.packages` or `environment.systemPackages` by `(gdb.override { enableDebuginfod = true })` in `/etc/nixos/configuration.nix` or `~/.config/nixpkgs/home.nix`. Don't use an overlay, as `gdb` is a mass rebuild. 128 | 129 | #### `valgrind` 130 | 131 | `valgrind` needs `debuginfod-find` on `$PATH` to use `nixseparatedebuginfod`. 132 | Add `(lib.getBin (pkgs.elfutils.override { enableDebuginfod = true; }))` to 133 | `environment.systemPackages` or `home.packages`. 134 | 135 | ### Check that it works 136 | 137 | `nix` is built with `separateDebugInfo`. 138 | ```commands 139 | $ gdb $(command -v nix) 140 | GNU gdb (GDB) 12.1 141 | Copyright (C) 2022 Free Software Foundation, Inc. 142 | License GPLv3+: GNU GPL version 3 or later 143 | This is free software: you are free to change and redistribute it. 144 | There is NO WARRANTY, to the extent permitted by law. 145 | Type "show copying" and "show warranty" for details. 146 | This GDB was configured as "x86_64-unknown-linux-gnu". 147 | Type "show configuration" for configuration details. 148 | For bug reporting instructions, please see: 149 | . 150 | Find the GDB manual and other documentation resources online at: 151 | . 152 | 153 | For help, type "help". 154 | Type "apropos word" to search for commands related to "word"... 155 | Reading symbols from /run/current-system/sw/bin/nix... 156 | Downloading 22.56 MB separate debug info for /run/current-system/sw/bin/nix 157 | Reading symbols from /home/symphorien/.cache/debuginfod_client/6d059e78eed4c79126bc9be93c612f9149a8deea/debuginfo... 158 | (gdb) start 159 | Downloading 0.01 MB source file /build/source/src/nix/main.cc 160 | Temporary breakpoint 1 at 0x97670: file src/nix/main.cc, line 401. 161 | Starting program: /nix/store/hfnwjdjm5h45pm64414hv2fh4kcx76zi-system-path/bin/nix 162 | Downloading 0.70 MB separate debug info for /nix/store/9xfad3b5z4y00mzmk2wnn4900q0qmxns-glibc-2.35-224/lib/ld-linux-x86-64.so.2 163 | Downloading 0.77 MB separate debug info for /nix/store/adyrxq2jq1jq3116jxhbcsb13wi6nzpq-libsodium-1.0.18/lib/libsodium.so.23 164 | Downloading 14.16 MB separate debug info for /nix/store/xb66g3x4iv7m95mja9zzi1ghhraxmpws-nix-2.11.1/lib/libnixexpr.so 165 | Downloading 0.23 MB separate debug info for /nix/store/688nq54x7kks8y7dn52nwsklnww19fxa-boehm-gc-8.2.2/lib/libgc.so.1 166 | Downloading 0.01 MB separate debug info for /nix/store/9xfad3b5z4y00mzmk2wnn4900q0qmxns-glibc-2.35-224/lib/libpthread.so.0 167 | Downloading 0.01 MB separate debug info for /nix/store/9xfad3b5z4y00mzmk2wnn4900q0qmxns-glibc-2.35-224/lib/libdl.so.2 168 | Downloading 1.27 MB separate debug info for /nix/store/xb66g3x4iv7m95mja9zzi1ghhraxmpws-nix-2.11.1/lib/libnixmain.so 169 | Downloading 4.97 MB separate debug info for /nix/store/xb66g3x4iv7m95mja9zzi1ghhraxmpws-nix-2.11.1/lib/libnixfetchers.so 170 | Downloading 21.73 MB separate debug info for /nix/store/xb66g3x4iv7m95mja9zzi1ghhraxmpws-nix-2.11.1/lib/libnixstore.so 171 | Downloading 5.69 MB separate debug info for /nix/store/xb66g3x4iv7m95mja9zzi1ghhraxmpws-nix-2.11.1/lib/libnixutil.so 172 | Downloading 3.83 MB separate debug info for /nix/store/xb66g3x4iv7m95mja9zzi1ghhraxmpws-nix-2.11.1/lib/libnixcmd.so 173 | Downloading 0.89 MB separate debug info for /nix/store/9xfad3b5z4y00mzmk2wnn4900q0qmxns-glibc-2.35-224/lib/libm.so.6 174 | Downloading 5.36 MB separate debug info for /nix/store/9xfad3b5z4y00mzmk2wnn4900q0qmxns-glibc-2.35-224/lib/libc.so.6 175 | [Thread debugging using libthread_db enabled] 176 | Using host libthread_db library "/nix/store/9xfad3b5z4y00mzmk2wnn4900q0qmxns-glibc-2.35-224/lib/libthread_db.so.1". 177 | Downloading 5.27 MB separate debug info for /nix/store/bprhh8afhvz27b051y8j451fyp6mkk38-openssl-3.0.7/lib/libcrypto.so.3 178 | Downloading 2.25 MB separate debug info for /nix/store/brmjip0wviknyi75bqddyda45m1rnw2i-sqlite-3.39.4/lib/libsqlite3.so.0 179 | Downloading 1.73 MB separate debug info for /nix/store/xryxkg022p5vnlyyyx58csbmfc7ydsdp-curl-7.86.0/lib/libcurl.so.4 180 | Downloading 0.01 MB separate debug info for /nix/store/9xfad3b5z4y00mzmk2wnn4900q0qmxns-glibc-2.35-224/lib/librt.so.1 181 | Downloading 1.07 MB separate debug info for /nix/store/bprhh8afhvz27b051y8j451fyp6mkk38-openssl-3.0.7/lib/libssl.so.3 182 | Downloading 0.11 MB separate debug info for /nix/store/9xfad3b5z4y00mzmk2wnn4900q0qmxns-glibc-2.35-224/lib/libresolv.so.2 183 | 184 | Temporary breakpoint 1, main (BFD: reopening /home/symphorien/.cache/debuginfod_client/3d6884d200ead572b7b89a4133f645c7a3c039ed/debuginfo: No such file or directory 185 | 186 | BFD: reopening /home/symphorien/.cache/debuginfod_client/3d6884d200ead572b7b89a4133f645c7a3c039ed/debuginfo: No such file or directory 187 | 188 | BFD: reopening /home/symphorien/.cache/debuginfod_client/3d6884d200ead572b7b89a4133f645c7a3c039ed/debuginfo: No such file or directory 189 | 190 | warning: Can't read data for section '.debug_loc' in file '/home/symphorien/.cache/debuginfod_client/3d6884d200ead572b7b89a4133f645c7a3c039ed/debuginfo' 191 | argc=1, argv=0x7fffffffd128) at src/nix/main.cc:401 192 | Downloading 0.01 MB source file /build/source/src/nix/main.cc 193 | 401 { 194 | (gdb) l 195 | 396 } 196 | 397 197 | 398 } 198 | 399 199 | 400 int main(int argc, char * * argv) 200 | 401 { 201 | 402 // Increase the default stack size for the evaluator and for 202 | 403 // libstdc++'s std::regex. 203 | 404 nix::setStackSize(64 * 1024 * 1024); 204 | 405 205 | (gdb) 206 | ``` 207 | 208 | ## Limitations 209 | - `nixseparatedebuginfod` only provides debug symbols for derivations built with `separateDebugInfo` set to `true`, obviously. 210 | - GDB only queries source files to `debuginfod` servers if the debug symbols were also provided via `debuginfod`, so `nixseparatedebuginfod` does not provide source for store paths with non-separate debug symbols (e.g. produced with `enableDebugging`). 211 | - `nixseparatedebuginfod` only finds the debug outputs of store paths if either a binary cache has indexed it (the same technique as `dwarffs`) or the `.drv` file is present on the system or substitutable. This should cover most cases, however. 212 | - Source fetching does not work when only the `dwarffs` can be used. 213 | - If a derivation patches a source file before compiling it, `nixseparatedebuginfod` will serve the unpatched source file straight from the `src` attribute of the derivation. 214 | - The `section` endpoint of the `debuginfod` protocol is not implemented. (If you know of some client that uses it, tell me). 215 | - Nix >= 2.18 is required to fetch sources successfully in some situations (notably 216 | when the program was fetched from hydra long after it was built). 217 | - Software compiled with the `stdenv` of NixOS 23.11 has mangled debug symbols where the store path of the source of in-lined functions/template instantiations is replaced by `/nix/store/eeeeee...`. These source files will not be fetched by `nixseparatedebuginfod`. The issue will be fixed in NixOS 24.05. 218 | 219 | ## Comparison to other ways to provide debug symbols 220 | - the `environment.enableDebugInfo = true;` NixOS option only provides debug symbols for software installed in `environment.systemPackages`, but not inner libraries. As a result you will get debug symbols for `qemu`, but not for the `glibc` it uses. It also downloads debug symbols even if you end up not using them, and `qemu` debug symbols take very long to download... 221 | - [`dwarffs`](https://github.com/edolstra/dwarffs) downloads debug symbols on the fly from a custom API provided by hydra. You won't get debug symbols for derivations compiled locally or on a custom binary cache. It also does not point `gdb` to the right place to find source files. 222 | - `nixseparatedebuginfod` supports all binary caches because it just uses the `nix-store` command line tool. It can serve sources files as well (see the section about limitations, though). This relies on `.drv` files being present or substitutable, but when this is not the case `nixseparatedebuginfod` can fall back to the same mechanism as `dwarffs` (no source). 223 | 224 | ## Security 225 | 226 | Normal operation uses `nix-*` commands and is subject to the normal nix control of substituter trust and NAR signing. However, anything that can connect to `nixseparatedebuginfod` gets some of the privilege of `nixseparatedebuginfod`: if you prohibit some users from using nix with the `allowed-users` option, these users can use `nixseparatedebuginfod` to 227 | - add files from binary caches into your store, 228 | - build existing `.drv` files, but not create new ones. 229 | When the `.drv` file of a store path is not found, `nixseparatedebuginfod` will fall back to same API as `dwarffs`. It serves NARs with debug symbols without signatures. This means that `nixseparatedebuginfod` may add NARs from any `file`, `http` and `https` substituters (trusted or not) in the output of `nix show-config` to your store without checking signatures. 230 | 231 | ## Notes 232 | 233 | An indexation step is needed on first startup, and then periodically. It happens automatically but can take a few minutes. A cache is stored somewhere in `~/.cache/nixseparatedebuginfod`, and currently this cache can only grow. You can safely remove it, it will be recreated on next startup. 234 | 235 | The `debuginfod` client provided by `elfutils` (used in `gdb`) caches `debuginfod` misses, and the only way to prevent this is to return `406 File too big`. If `gdb` requests something during initial indexation you will see spurious complaints about `File too big`. You can ignore them, and retry later is debug symbols are missing. 236 | (For development, it is useful to disable this cache altogether: 237 | write 0 to `~/.cache/debuginfod_client/cache_miss_s` and `~/.cache/debuginfod_client/max_unused_age_s` and `~/.cache/debuginfod_client/cache_clean_interval_s`. However, this breaks `gdb` back traces in weird ways.) 238 | 239 | To make `nixseparatedebuginfod` less verbose, export `RUST_LOG=warn` or `RUST_LOG=error`. 240 | 241 | ## Troubleshooting 242 | 243 | If you do not use the provided NixOS module and `nixseparatedebuginfod` fails to start because the nix daemon resets the connection like this: 244 | ``` 245 | 2023-09-25T21:48:52.750 5006851216 nix-daemon.service nix-daemon[216134] INFO error: error processing connection: user 'nixseparatedebuginfod' is not allowed to connect to the Nix daemon 246 | 2023-09-25T21:48:52.752 5006852674 nixseparatedebuginfod.service nixseparatedebuginfod[216414] INFO 2023-09-25T19:48:52.752187Z ERROR nixseparatedebuginfod: nix is not available: checking nix install by getting deriver of /nix/store/9krlzvny65gdc8s7kpb6lkx8cd02c25b-default-builder.sh: "nix-store" "--query" "--deriver" "/nix/store/9krlzvny65gdc8s7kpb6lkx8cd02c25b-default-builder.sh" failed: error: cannot open connection to remote store 'daemon': error: reading from file: Connection reset by peer 247 | ``` 248 | then you probably have restricted access to the daemon to specific users, for example 249 | with `nix.settings.allowed-users = [ "@somegroup" ];`. Add the user `nixseparatedebuginfod` runs as 250 | to this list. You can check that the setting had effect with `nix show-config`. 251 | 252 | ## References 253 | Protocol: 254 | Client cache: 255 | -------------------------------------------------------------------------------- /src/substituter.rs: -------------------------------------------------------------------------------- 1 | //! Access to debuginfo indexed in binary caches created with 2 | //! `?index-debug-info=true`, for example Hydra. 3 | //! 4 | //! This is the API that dwarffs uses. When nars are copied to the binary cache, 5 | //! file in the for `$out/lib/debug/.build-id/sh/a1` are symlinked into `debuginfo/sha1` 6 | //! (on hydra) or `debuginfo/sha1.debug` (for file:/// caches crated with nix-copy). 7 | //! The actual nature of the symnlink can vary: it may be a json file. 8 | 9 | use std::{ 10 | collections::hash_map::DefaultHasher, 11 | ffi::OsStr, 12 | hash::{Hash, Hasher}, 13 | io::{BufReader, Read}, 14 | os::unix::prelude::OsStrExt, 15 | path::{Path, PathBuf}, 16 | }; 17 | 18 | use anyhow::Context; 19 | use async_recursion::async_recursion; 20 | use async_trait::async_trait; 21 | use futures_util::StreamExt; 22 | use reqwest::StatusCode; 23 | use reqwest::Url; 24 | use serde::Deserialize; 25 | use tempfile::TempDir; 26 | use tokio::io::{AsyncWriteExt, BufWriter}; 27 | 28 | use crate::store::{get_buildid, get_store_path}; 29 | 30 | #[derive(Deserialize)] 31 | struct DebuginfoMetadata { 32 | /// the relative path of the nar.xz in this substituter 33 | archive: String, 34 | /// the file inside the nar that holds the debuginfo 35 | #[allow(dead_code)] 36 | member: String, 37 | } 38 | 39 | /// Returns the 32 first bytes of the specified file 40 | async fn magic(path: &Path) -> anyhow::Result> { 41 | let mut res = vec![b'\0'; 32]; 42 | let mut file = std::fs::File::open(path) 43 | .with_context(|| format!("reading magic of {}", path.display()))?; 44 | file.read_exact(&mut res[..]) 45 | .with_context(|| format!("reading start of {} to determine magic", path.display()))?; 46 | Ok(res) 47 | } 48 | 49 | const NAR_MAGIC: &[u8] = b"\x0d\x00\x00\x00\x00\x00\x00\x00nix-archive-1"; 50 | const ELF_MAGIC: &[u8] = b"\x7fELF"; 51 | 52 | /// API to fetch debuginfo indices from substituters 53 | #[async_trait] 54 | pub trait Substituter: Send + Sync { 55 | /// Fetches a file from the substituter indexed by its relative path 56 | /// to the root 57 | /// 58 | /// Returns None in case of missing file. 59 | async fn fetch(&self, path: &Path) -> anyhow::Result>; 60 | 61 | /// the url used to construct this substituter 62 | fn url(&self) -> &str; 63 | } 64 | 65 | /// returns a store path containing the requested debuginfo in 66 | /// `/lib/debug/.build-id` 67 | pub async fn fetch_debuginfo( 68 | substituter: &T, 69 | buildid: &str, 70 | ) -> anyhow::Result> { 71 | let mut res = Ok(None); 72 | for path in [ 73 | // for hydra 74 | PathBuf::from(format!("debuginfo/{buildid}")), 75 | // for file:///path?index-debug-info=true created with nix copy 76 | PathBuf::from(format!("debuginfo/{buildid}.debug")), 77 | ] 78 | .into_iter() 79 | { 80 | res = fetch_debuginfo_from(substituter, path.as_path(), 2).await; 81 | if let Ok(Some(path)) = &res { 82 | tracing::info!( 83 | "downloaded debuginfo for {} from {} into {}", 84 | buildid, 85 | substituter.url(), 86 | path.display() 87 | ); 88 | break; 89 | } 90 | } 91 | res 92 | } 93 | 94 | /// attempt to fetch debuginfo in this relative path inside the substituter 95 | /// 96 | /// returns a store path containing it 97 | #[allow(clippy::multiple_bound_locations)] 98 | #[async_recursion] 99 | async fn fetch_debuginfo_from( 100 | substituter: &T, 101 | path: &Path, 102 | max_redirects: usize, 103 | ) -> anyhow::Result> { 104 | tracing::debug!( 105 | "attempting to fetch {} from {}", 106 | path.display(), 107 | substituter.url() 108 | ); 109 | let file = substituter 110 | .fetch(path) 111 | .await 112 | .with_context(|| format!("fetching {} from {}", path.display(), substituter.url()))?; 113 | let file = match file { 114 | None => return Ok(None), 115 | Some(f) => f, 116 | }; 117 | let tempdir; 118 | let temppath; 119 | let target; 120 | // the logic below is taken from dwarffs, but hydra only uses json redirection -> nar.xz 121 | let dir_to_add = match &magic(file.as_path()).await? { 122 | m if m.starts_with(ELF_MAGIC) => { 123 | /* This is the debuginfo file we want. 124 | * Let's create the expected hierarchy `lib/debug/.buildid/aa/bbbbbbbb` 125 | */ 126 | // sync code 127 | let buildid = match get_buildid(file.as_path()).with_context(|| { 128 | format!( 129 | "buildid of elf file fetched from {} in {}", 130 | path.display(), 131 | substituter.url() 132 | ) 133 | })? { 134 | None => anyhow::bail!( 135 | "fetched elf file from {} in {} but it has no build id", 136 | path.display(), 137 | substituter.url() 138 | ), 139 | Some(x) => x, 140 | }; 141 | let dir = TempDir::new().context("tempdir")?; 142 | target = dir.path().join("target-nar"); 143 | let mut parent = target.join("lib/debug/.build-id"); 144 | parent.push(&buildid[..2]); 145 | tokio::fs::create_dir_all(parent.as_path()) 146 | .await 147 | .with_context(|| format!("creating {}", parent.display()))?; 148 | parent.push(format!("{}.debug", &buildid[2..])); 149 | tokio::fs::copy(file.as_path(), parent.as_path()) 150 | .await 151 | .context("copying debuginfo file")?; 152 | target.as_path() 153 | } 154 | m if m.starts_with(b"{") => { 155 | /***************** 156 | * this is a json redirect 157 | *****************/ 158 | if max_redirects == 0 { 159 | anyhow::bail!("too many redirects"); 160 | } 161 | // sync code 162 | let file = std::fs::File::open(file.as_path()) 163 | .with_context(|| format!("opening {} to deserialize as json", path.display()))?; 164 | let bufread = BufReader::new(file); 165 | let metadata: DebuginfoMetadata = serde_json::from_reader(bufread) 166 | .with_context(|| format!("parsing {} as json", path.display()))?; 167 | let mut redirect_path = match path.parent() { 168 | None => PathBuf::from("."), 169 | Some(p) => p.to_path_buf(), 170 | }; 171 | redirect_path.push(&metadata.archive); 172 | anyhow::ensure!( 173 | redirect_path.is_relative(), 174 | "debuginfo metadata {} from {} features an absolute path {}", 175 | path.display(), 176 | substituter.url(), 177 | &metadata.archive 178 | ); 179 | return fetch_debuginfo_from(substituter, redirect_path.as_path(), max_redirects - 1) 180 | .await; 181 | } 182 | m => { 183 | let nar_file = if m.starts_with(NAR_MAGIC) { 184 | /*********** 185 | * this is the nar file containing the debuginfo 186 | **********/ 187 | file.as_path() // a nar file 188 | } else { 189 | /*********** 190 | * this is a compressed nar probably 191 | **********/ 192 | temppath = tempfile::NamedTempFile::new() 193 | .context("temppath")? 194 | .into_temp_path(); 195 | let out = tokio::fs::File::create(&temppath) 196 | .await 197 | .context("opening temppath")?; 198 | let fd = tokio::fs::File::open(&file).await.context("unxz")?; 199 | compress_tools::tokio_support::uncompress_data(fd, out) 200 | .await 201 | .with_context(|| { 202 | format!("unpacking {} from {}", file.display(), substituter.url()) 203 | })?; 204 | if magic(temppath.as_ref()) 205 | .await 206 | .context("magic of uncompressed nar")? 207 | .starts_with(NAR_MAGIC) 208 | { 209 | temppath.as_ref() 210 | } else { 211 | anyhow::bail!("nar {} was not a compressed nar", path.display()); 212 | } 213 | }; 214 | // unpack the nar 215 | let fd = tokio::fs::File::open(nar_file).await?; 216 | let mut cmd = tokio::process::Command::new("nix-store"); 217 | cmd.arg("--restore"); 218 | tempdir = tempfile::TempDir::new().context("tempdir")?; 219 | // FIXME: the indexer should probably not take the name of the store path into account 220 | target = tempdir.as_ref().join("nar-debug"); 221 | cmd.arg(target.as_path()); 222 | cmd.stdin(fd.into_std().await); 223 | let status = cmd.status().await.with_context(|| { 224 | format!( 225 | "running nix-store --import to unpack nar from {} in {}", 226 | nar_file.display(), 227 | substituter.url() 228 | ) 229 | })?; 230 | anyhow::ensure!(status.success(), "nix-store --import failed: {:?}", status); 231 | anyhow::ensure!( 232 | target.exists(), 233 | "nix-store --import failed to create {}", 234 | target.display() 235 | ); 236 | 237 | target.as_path() 238 | } 239 | }; 240 | 241 | // add it to the store 242 | let mut cmd = tokio::process::Command::new("nix-store"); 243 | cmd.arg("--add"); 244 | cmd.arg(dir_to_add); 245 | let output = cmd.output().await.context("nix-store --add")?; 246 | anyhow::ensure!( 247 | output.status.success(), 248 | "nix-store --add failed: {:?}: {}", 249 | output.status, 250 | String::from_utf8_lossy(&output.stderr) 251 | ); 252 | let mut storepath = &output.stdout[..]; 253 | if storepath.ends_with(b"\n") { 254 | storepath = &storepath[..(storepath.len() - 1)]; 255 | } 256 | let storepath = Path::new::(OsStrExt::from_bytes(storepath)); 257 | match get_store_path(storepath) { 258 | None => anyhow::bail!( 259 | "nix-store --add did not return a store path but «{}»", 260 | storepath.display() 261 | ), 262 | Some(s) => { 263 | anyhow::ensure!(s.exists(), "nix-store --add failed to produce a storepath"); 264 | Ok(Some(s.to_path_buf())) 265 | } 266 | } 267 | } 268 | 269 | /// A file:/// substituter 270 | #[derive(PartialEq, Eq, Debug)] 271 | pub struct FileSubstituter { 272 | // root path of the substituter 273 | path: PathBuf, 274 | // url of the substituter 275 | url: String, 276 | } 277 | 278 | impl FileSubstituter { 279 | /// If this url starts with file:/// and is a real path then returns an instance, otherwise 280 | /// None 281 | pub async fn from_url(url: &str) -> anyhow::Result> { 282 | let parsed_url = 283 | Url::parse(url).with_context(|| format!("parsing binary cache url {url}"))?; 284 | if parsed_url.scheme() != "file" { 285 | return Ok(None); 286 | } 287 | let path = parsed_url 288 | .to_file_path() 289 | .map_err(|_| anyhow::anyhow!("cannot convert {} to file path", url))?; 290 | let path = path.canonicalize().with_context(|| { 291 | format!( 292 | "resolving directory {} of substituter {}", 293 | path.display(), 294 | url 295 | ) 296 | })?; 297 | Ok(Some(FileSubstituter { 298 | path, 299 | url: url.to_owned(), 300 | })) 301 | } 302 | } 303 | 304 | #[async_trait] 305 | impl Substituter for FileSubstituter { 306 | async fn fetch(&self, path: &Path) -> anyhow::Result> { 307 | anyhow::ensure!( 308 | path.is_relative(), 309 | "substituter path {} should be relative", 310 | path.display() 311 | ); 312 | let path = self.path.join(path); 313 | if path.exists() { 314 | Ok(Some(path)) 315 | } else { 316 | Ok(None) 317 | } 318 | } 319 | 320 | fn url(&self) -> &str { 321 | &self.url 322 | } 323 | } 324 | 325 | #[tokio::test] 326 | async fn file_substituter_from_url() { 327 | let d = TempDir::new().unwrap(); 328 | assert!(matches!( 329 | FileSubstituter::from_url("https://cache.nixos.rg").await, 330 | Ok(None) 331 | )); 332 | assert!( 333 | FileSubstituter::from_url(&format!("file://{}/doesnotexist", d.path().display())) 334 | .await 335 | .is_err() 336 | ); 337 | let ok = FileSubstituter::from_url(&format!( 338 | "file://{}/./?with_query_string=true", 339 | d.path().display() 340 | )) 341 | .await 342 | .unwrap() 343 | .unwrap(); 344 | assert_eq!(&ok.path, d.path()); 345 | } 346 | 347 | #[tokio::test] 348 | async fn file_substituter_fetch() { 349 | let d = TempDir::new().unwrap(); 350 | let ok = FileSubstituter::from_url(&format!("file://{}/./?yay=bar", d.path().display())) 351 | .await 352 | .unwrap() 353 | .unwrap(); 354 | let path = d.path().join("file"); 355 | std::fs::write(&path, "yay").unwrap(); 356 | assert_eq!(ok.fetch(Path::new("./file")).await.unwrap().unwrap(), path); 357 | } 358 | 359 | /// A https:/// substituter 360 | #[derive(Debug)] 361 | pub struct HttpSubstituter { 362 | // The url to contact the cache, without its nix-specific query string, and with a trailing 363 | // slash 364 | http_url: Url, 365 | // url of the substituter, as passed to from_url 366 | url: String, 367 | client: reqwest::Client, 368 | cache: TempDir, 369 | } 370 | 371 | impl HttpSubstituter { 372 | /// If this url starts with file:/// and is a real path then returns an instance, otherwise 373 | /// None 374 | pub async fn from_url(url: &str) -> anyhow::Result> { 375 | let mut http_url = 376 | Url::parse(url).with_context(|| format!("parsing binary cache url {url}"))?; 377 | match http_url.scheme() { 378 | "http" | "https" => (), 379 | _ => return Ok(None), 380 | }; 381 | 382 | http_url.set_query(None); 383 | if !http_url.path().ends_with('/') { 384 | let mut path = http_url.path().to_owned(); 385 | path.push('/'); 386 | http_url.set_path(&path); 387 | } 388 | 389 | let cache = TempDir::new().context("tempdir")?; 390 | let client = reqwest::Client::new(); 391 | 392 | Ok(Some(HttpSubstituter { 393 | http_url, 394 | url: url.to_owned(), 395 | cache, 396 | client, 397 | })) 398 | } 399 | } 400 | 401 | #[async_trait] 402 | impl Substituter for HttpSubstituter { 403 | async fn fetch(&self, path: &Path) -> anyhow::Result> { 404 | anyhow::ensure!( 405 | path.is_relative(), 406 | "substituter path {} should be relative", 407 | path.display() 408 | ); 409 | let path_str = path 410 | .to_str() 411 | .ok_or_else(|| anyhow::anyhow!("invalid path {}", path.display()))?; 412 | let url = self 413 | .http_url 414 | .join(path_str) 415 | .with_context(|| format!("cannot join {} to {}", path_str, &self.http_url))?; 416 | 417 | let mut hasher = DefaultHasher::default(); 418 | url.hash(&mut hasher); 419 | let hash = hasher.finish(); 420 | let cache_path = self.cache.path().join(format!("{hash:x}")); 421 | 422 | if cache_path.exists() { 423 | return Ok(Some(cache_path)); 424 | } 425 | 426 | let tmp = tempfile::TempPath::from_path(self.cache.path().join(format!("{hash:x}.part"))); 427 | let fd = tokio::fs::File::create(&tmp).await.context("temp file")?; 428 | let mut write = BufWriter::new(fd); 429 | 430 | tracing::debug!("getting {}", &url); 431 | let response = match self.client.get(url.as_str()).send().await { 432 | Ok(r) if r.status() == StatusCode::NOT_FOUND => { 433 | tracing::debug!("{} not found in {}", path.display(), self.url()); 434 | return Ok(None); 435 | } 436 | Err(e) if e.status() == Some(StatusCode::NOT_FOUND) => { 437 | tracing::debug!("{} not found in {}", path.display(), self.url()); 438 | return Ok(None); 439 | } 440 | Ok(r) if r.status() != StatusCode::OK => { 441 | tracing::warn!("unexpected status {} for {}", r.status(), &url); 442 | anyhow::bail!("{} returned status {}", self.url(), r.status()); 443 | } 444 | Ok(r) => r, 445 | Err(e) => anyhow::bail!( 446 | "cannot fetch {} for {} in {}: {:#}", 447 | &url, 448 | path.display(), 449 | self.url(), 450 | e 451 | ), 452 | }; 453 | let mut body = response.bytes_stream(); 454 | 455 | while let Some(chunk) = body.next().await { 456 | let chunk = chunk.with_context(|| { 457 | format!( 458 | "downloading from {} for {} in {}", 459 | &url, 460 | path.display(), 461 | self.url() 462 | ) 463 | })?; 464 | write 465 | .write_all(&chunk) 466 | .await 467 | .context("writing to tmp file")?; 468 | } 469 | 470 | write.flush().await.context("writing to disk")?; 471 | write.into_inner().sync_data().await.context("syncing")?; 472 | 473 | tmp.persist(&cache_path).context("renaming temp file")?; 474 | 475 | Ok(Some(cache_path)) 476 | } 477 | 478 | fn url(&self) -> &str { 479 | &self.url 480 | } 481 | } 482 | -------------------------------------------------------------------------------- /src/server.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: 2023 Guillaume Girol 2 | // 3 | // SPDX-License-Identifier: GPL-3.0-only 4 | 5 | //! An http server serving the content of [Cache] 6 | //! 7 | //! References: 8 | //! Protocol: 9 | 10 | use anyhow::Context; 11 | use axum::body::Body; 12 | use axum::extract::{Path, State}; 13 | use axum::http::StatusCode; 14 | use axum::response::IntoResponse; 15 | use axum::{routing::get, Router}; 16 | use http::header::{HeaderMap, CONTENT_LENGTH}; 17 | use std::collections::HashSet; 18 | use std::os::unix::prelude::MetadataExt; 19 | use std::path::PathBuf; 20 | use std::process::ExitCode; 21 | use std::sync::Arc; 22 | use std::time::Duration; 23 | use tokio_util::io::ReaderStream; 24 | 25 | use crate::db::Cache; 26 | use crate::index::{index_single_store_path_to_cache, StoreWatcher}; 27 | use crate::log::ResultExt; 28 | use crate::store::{ 29 | demangle, get_file_for_source, get_store_path, open_store_path, realise, SourceLocation, 30 | }; 31 | use crate::substituter::{FileSubstituter, HttpSubstituter, Substituter}; 32 | use crate::Options; 33 | 34 | #[derive(Clone)] 35 | struct ServerState { 36 | cache: Cache, 37 | watcher: StoreWatcher, 38 | substituters: Arc>>, 39 | } 40 | 41 | /// The only status code in the client code of debuginfod in elfutils that prevents 42 | /// creation of a negative cache entry. 43 | /// 44 | /// 503 Not Available also works, but only for the section request 45 | const NON_CACHING_ERROR_STATUS: StatusCode = StatusCode::NOT_ACCEPTABLE; 46 | 47 | /// Serve the content of this file, or an appropriate error. 48 | /// 49 | /// Attempts to substitute the file if necessary. 50 | /// 51 | /// `ready` should be true if indexation is currently complete. If it is false, 52 | /// error codes are tuned to prevent the client from caching the answer. 53 | async fn unwrap_file>( 54 | path: anyhow::Result>, 55 | ready: bool, 56 | ) -> impl IntoResponse { 57 | let response = match path { 58 | Ok(Some(p)) => { 59 | let fd = open_store_path(&p); 60 | match fd.map(tokio::fs::File::from) { 61 | Err(e) => Err((StatusCode::NOT_FOUND, format!("{:#}", e))), 62 | Ok(file) => { 63 | let mut headers = HeaderMap::new(); 64 | if let Ok(metadata) = file.metadata().await { 65 | if let Ok(value) = metadata.size().to_string().parse() { 66 | headers.insert(CONTENT_LENGTH, value); 67 | } 68 | } 69 | tracing::info!("returning {}", p.as_ref().display()); 70 | // convert the `AsyncRead` into a `Stream` 71 | let stream = ReaderStream::new(file); 72 | // convert the `Stream` into an `axum::body::HttpBody` 73 | let body = Body::from_stream(stream); 74 | Ok((headers, body)) 75 | } 76 | } 77 | } 78 | Ok(None) => Err(( 79 | if ready { 80 | StatusCode::NOT_FOUND 81 | } else { 82 | NON_CACHING_ERROR_STATUS 83 | }, 84 | "not found in cache".to_string(), 85 | )), 86 | Err(e) => Err((StatusCode::NOT_FOUND, format!("{:#}", e))), 87 | }; 88 | if let Err((code, error)) = &response { 89 | tracing::info!("Responding error {}: {}", code, error); 90 | }; 91 | response 92 | } 93 | 94 | /// Start indexation, and wait for it to complete until timeout. 95 | /// 96 | /// Returns whether indexation is complete. 97 | async fn start_indexation_and_wait(watcher: StoreWatcher, timeout: Duration) -> bool { 98 | match watcher.maybe_index_new_paths().await { 99 | Err(e) => { 100 | tracing::warn!("cannot start registration of new store path: {:#}", e); 101 | false 102 | } 103 | Ok(None) => true, 104 | Ok(Some(handle)) => { 105 | tokio::select! { 106 | _ = tokio::time::sleep(timeout) => false, 107 | _ = handle => true, 108 | } 109 | } 110 | } 111 | } 112 | 113 | /// Reindex harder. 114 | /// 115 | /// If the .drv file is not in the store, automatic indexation will find the executable but not 116 | /// the debuginfo and source. We can attempt to download this drv file during a second 117 | /// indexation attempt. 118 | async fn maybe_reindex_by_build_id(cache: &Cache, buildid: &str) -> anyhow::Result<()> { 119 | let exe = match cache 120 | .get_executable(buildid) 121 | .await 122 | .with_context(|| format!("getting executable of {} from cache", buildid))? 123 | { 124 | Some(exe) => exe, 125 | None => return Ok(()), 126 | }; 127 | tracing::debug!("reindexing {}", &exe); 128 | let exe = PathBuf::from(exe); 129 | let storepath = match get_store_path(exe.as_path()) { 130 | Some(storepath) => storepath, 131 | None => anyhow::bail!( 132 | "executable {} for buildid {} is not a store path", 133 | exe.display(), 134 | buildid 135 | ), 136 | }; 137 | index_single_store_path_to_cache(cache, storepath, true) 138 | .await 139 | .with_context(|| format!("indexing {} online", exe.display()))?; 140 | Ok(()) 141 | } 142 | 143 | /// Ensures that the contained path exists, and if this is not the case 144 | /// replace it by `Ok(None)` 145 | /// 146 | /// The tag is the kind of file this should be, to be used in error messages 147 | async fn and_realise>( 148 | result: anyhow::Result>, 149 | tag: &str, 150 | ) -> anyhow::Result> { 151 | match result { 152 | Ok(Some(p)) => { 153 | let res = realise(p.as_ref()) 154 | .await 155 | .with_context(|| format!("realising {} of type {}", p.as_ref().display(), tag)); 156 | 157 | if res.is_err() { 158 | res.or_warn(); 159 | Ok(None) 160 | } else { 161 | Ok(Some(p)) 162 | } 163 | } 164 | other => other, 165 | } 166 | } 167 | 168 | /// attempts to fetch debuginfo from substituters via the same API as dwarffs 169 | async fn maybe_fetch_debuginfo_from_substituter_index( 170 | cache: &Cache, 171 | substituters: &[Box], 172 | buildid: &str, 173 | ) -> anyhow::Result<()> { 174 | for substituter in substituters.iter() { 175 | match crate::substituter::fetch_debuginfo(substituter.as_ref(), buildid).await { 176 | Err(e) => tracing::info!( 177 | "cannot fetch buildid {} from substituter {}: {:#}", 178 | buildid, 179 | substituter.url(), 180 | e 181 | ), 182 | Ok(None) => (), 183 | Ok(Some(path)) => { 184 | tracing::info!( 185 | "fetched {} from substituter {}, now indexing it", 186 | path.display(), 187 | substituter.url() 188 | ); 189 | index_single_store_path_to_cache(cache, &path, false) 190 | .await 191 | .with_context(|| format!("indexing {}", path.display())) 192 | .or_warn(); 193 | if let Ok(Some(_)) = 194 | and_realise(cache.get_debuginfo(buildid).await, "debuginfo").await 195 | { 196 | break; 197 | } 198 | } 199 | } 200 | } 201 | Ok(()) 202 | } 203 | 204 | /// How long to wait for indexation to complete before serving the cache 205 | const INDEXING_TIMEOUT: Duration = Duration::from_secs(1); 206 | 207 | #[axum_macros::debug_handler] 208 | async fn get_debuginfo( 209 | Path(buildid): Path, 210 | State(state): State, 211 | ) -> impl IntoResponse { 212 | let ready = start_indexation_and_wait(state.watcher, INDEXING_TIMEOUT).await; 213 | let res = and_realise(state.cache.get_debuginfo(&buildid).await, "debuginfo").await; 214 | let res = match res { 215 | Ok(None) => { 216 | // try again harder 217 | tracing::debug!("{} was not in cache, reindexing online", buildid); 218 | match maybe_reindex_by_build_id(&state.cache, &buildid).await { 219 | Ok(()) => and_realise(state.cache.get_debuginfo(&buildid).await, "debuginfo").await, 220 | Err(e) => Err(e), 221 | } 222 | } 223 | res => res, 224 | }; 225 | let res = match res { 226 | Ok(None) => { 227 | // try again harder 228 | tracing::debug!( 229 | "online reindexation failed for {}, using hydra API", 230 | buildid 231 | ); 232 | match maybe_fetch_debuginfo_from_substituter_index( 233 | &state.cache, 234 | state.substituters.as_ref(), 235 | &buildid, 236 | ) 237 | .await 238 | { 239 | Ok(()) => and_realise(state.cache.get_debuginfo(&buildid).await, "debuginfo").await, 240 | Err(e) => Err(e), 241 | } 242 | } 243 | res => res, 244 | }; 245 | unwrap_file(res, ready).await 246 | } 247 | 248 | #[axum_macros::debug_handler] 249 | async fn get_executable( 250 | Path(buildid): Path, 251 | State(state): State, 252 | ) -> impl IntoResponse { 253 | let ready = start_indexation_and_wait(state.watcher, INDEXING_TIMEOUT).await; 254 | let res = and_realise(state.cache.get_executable(&buildid).await, "executable").await; 255 | unwrap_file(res, ready).await 256 | } 257 | 258 | /// queries the cache for a source file `request` corresponding to `buildid`. 259 | /// 260 | /// may download the source if required, and returns where the requested file is on disk. 261 | async fn fetch_and_get_source( 262 | buildid: String, 263 | request: PathBuf, 264 | cache: Cache, 265 | ) -> anyhow::Result> { 266 | let source = cache.get_source(&buildid).await; 267 | let source = match and_realise(source, "source").await { 268 | Ok(None) => { 269 | // try again harder 270 | match maybe_reindex_by_build_id(&cache, &buildid).await { 271 | Ok(()) => and_realise(cache.get_source(&buildid).await, "source").await, 272 | Err(e) => Err(e), 273 | } 274 | } 275 | source => source, 276 | }; 277 | let source = source.with_context(|| format!("getting source of {} from cache", &buildid))?; 278 | let source = match source { 279 | None => { 280 | tracing::debug!("no source found for buildid {}", &buildid); 281 | return Ok(None); 282 | } 283 | Some(x) => PathBuf::from(x), 284 | }; 285 | tracing::debug!( 286 | "found source store path for buildid {} at {}", 287 | &buildid, 288 | source.display() 289 | ); 290 | let file = 291 | tokio::task::spawn_blocking(move || get_file_for_source(source.as_ref(), request.as_ref())) 292 | .await? 293 | .context("looking in source")?; 294 | Ok(file) 295 | } 296 | 297 | /// reads a file inside an archive into an http response 298 | async fn uncompress_archive_file_to_http_body( 299 | archive: &std::path::Path, 300 | member: &std::path::Path, 301 | ) -> anyhow::Result { 302 | let archive_file = tokio::fs::File::open(&archive) 303 | .await 304 | .with_context(|| format!("opening source archive {}", archive.display()))?; 305 | let member_path = member 306 | .to_str() 307 | .ok_or_else(|| anyhow::anyhow!("non utf8 archive name"))? 308 | .to_string(); 309 | let (asyncwriter, asyncreader) = tokio::io::duplex(256 * 1024); 310 | let streamreader = tokio_util::io::ReaderStream::new(asyncreader); 311 | let archive = archive.to_path_buf(); 312 | let member = member.to_path_buf(); 313 | let decompressor_future = async move { 314 | if let Err(e) = compress_tools::tokio_support::uncompress_archive_file( 315 | archive_file, 316 | asyncwriter, 317 | &member_path, 318 | ) 319 | .await 320 | { 321 | tracing::error!( 322 | "expanding {} from {}: {:#}", 323 | member.display(), 324 | archive.display(), 325 | e 326 | ); 327 | } 328 | }; 329 | tokio::spawn(decompressor_future); 330 | Ok(Body::from_stream(streamreader)) 331 | } 332 | 333 | #[axum_macros::debug_handler] 334 | async fn get_source( 335 | Path((buildid, request)): Path<(String, String)>, 336 | State(state): State, 337 | ) -> impl IntoResponse { 338 | // when gdb attempts to show the source of a function that comes 339 | // from a header in another library, the request is store path made 340 | // relative to / 341 | // in this case, let's fetch it 342 | if request.starts_with("nix/store") { 343 | let absolute = PathBuf::from("/").join(request); 344 | let demangled = demangle(absolute); 345 | let error = realise(&demangled) 346 | .await 347 | .with_context(|| format!("downloading source {}", demangled.display())); 348 | return unwrap_file(error.map(|()| Some(demangled)), true) 349 | .await 350 | .into_response(); 351 | } 352 | // as a fallback, have a look at the source of the buildid 353 | let ready = start_indexation_and_wait(state.watcher, INDEXING_TIMEOUT).await; 354 | let request = PathBuf::from(request); 355 | let sourcefile = fetch_and_get_source(buildid.to_owned(), request, state.cache).await; 356 | let response = match sourcefile { 357 | Ok(Some(SourceLocation::File(path))) => match tokio::fs::File::open(&path).await { 358 | Err(e) => Err(( 359 | StatusCode::NOT_FOUND, 360 | format!("opening {}: {:#}", path.display(), e), 361 | )), 362 | Ok(file) => { 363 | let mut headers = HeaderMap::new(); 364 | if let Ok(metadata) = path.metadata() { 365 | if let Ok(value) = metadata.size().to_string().parse() { 366 | headers.insert(CONTENT_LENGTH, value); 367 | } 368 | } 369 | tracing::info!("returning {}", path.display()); 370 | // convert the `AsyncRead` into a `Stream` 371 | let stream = ReaderStream::new(file); 372 | // convert the `Stream` into an `axum::body::HttpBody` 373 | let body = Body::from_stream(stream); 374 | Ok((headers, body).into_response()) 375 | } 376 | }, 377 | Ok(Some(SourceLocation::Archive { 378 | ref archive, 379 | ref member, 380 | })) => match uncompress_archive_file_to_http_body(archive, member).await { 381 | Ok(r) => { 382 | tracing::info!("returning {} from {}", member.display(), archive.display()); 383 | Ok(r.into_response()) 384 | } 385 | Err(e) => Err((StatusCode::NOT_FOUND, format!("{:#}", e))), 386 | }, 387 | Ok(None) => Err(( 388 | if ready { 389 | StatusCode::NOT_FOUND 390 | } else { 391 | NON_CACHING_ERROR_STATUS 392 | }, 393 | "not found in cache".to_string(), 394 | )), 395 | Err(e) => Err((StatusCode::NOT_FOUND, format!("{:#}", e))), 396 | }; 397 | if let Err((code, error)) = &response { 398 | tracing::info!("Responding error {}: {}", code, error); 399 | }; 400 | response.into_response() 401 | } 402 | 403 | async fn get_section(Path(_param): Path<(String, String)>) -> impl IntoResponse { 404 | StatusCode::NOT_IMPLEMENTED 405 | } 406 | 407 | async fn get_substituters() -> anyhow::Result>> { 408 | let config = crate::config::get_nix_config() 409 | .await 410 | .context("determining the list of substituters")?; 411 | let mut urls = HashSet::new(); 412 | for key in &["substituters", "trusted-substituters"] { 413 | let several = config.get(*key).map(|s| s.as_str()).unwrap_or(""); 414 | for word in several.split(' ') { 415 | if !word.is_empty() { 416 | urls.insert(word); 417 | } 418 | } 419 | } 420 | tracing::debug!("found substituters {urls:?} in nix.conf"); 421 | let mut substituters: Vec> = vec![]; 422 | for url in urls.iter() { 423 | match FileSubstituter::from_url(url).await { 424 | Ok(Some(s)) => { 425 | tracing::debug!("using substituter {} for hydra API", s.url()); 426 | substituters.push(Box::new(s)); 427 | continue; 428 | } 429 | Err(e) => tracing::warn!("substituter url {url} has a problem: {e:#}"), 430 | Ok(None) => tracing::debug!("substituter {url} is not supported by file:// backend"), 431 | } 432 | match HttpSubstituter::from_url(url).await { 433 | Ok(Some(s)) => { 434 | tracing::debug!("using substituter {} for hydra API", s.url()); 435 | substituters.push(Box::new(s)); 436 | } 437 | Err(e) => tracing::warn!("substituter url {url} has a problem: {e:#}"), 438 | Ok(None) => tracing::debug!("substituter {url} is not supported by https:// backend"), 439 | } 440 | } 441 | Ok(substituters) 442 | } 443 | 444 | /// If option `-i` is specified, index and exit. Otherwise starts indexation and runs the 445 | /// debuginfod server. 446 | pub async fn run_server(args: Options) -> anyhow::Result { 447 | let cache = Cache::open().await.context("opening global cache")?; 448 | let watcher = StoreWatcher::new(cache.clone()); 449 | if args.index_only { 450 | match watcher.maybe_index_new_paths().await? { 451 | None => (), 452 | Some(handle) => handle.await?, 453 | }; 454 | Ok(ExitCode::SUCCESS) 455 | } else { 456 | watcher.watch_store(); 457 | let substituters = match get_substituters().await { 458 | Ok(l) => l, 459 | Err(e) => { 460 | tracing::warn!("could not determine the list of substituters: {e:#}"); 461 | vec![] 462 | } 463 | }; 464 | let state = ServerState { 465 | watcher, 466 | cache, 467 | substituters: Arc::new(substituters), 468 | }; 469 | let app = Router::new() 470 | .route("/buildid/:buildid/section/:section", get(get_section)) 471 | .route("/buildid/:buildid/source/*path", get(get_source)) 472 | .route("/buildid/:buildid/executable", get(get_executable)) 473 | .route("/buildid/:buildid/debuginfo", get(get_debuginfo)) 474 | .layer(tower_http::trace::TraceLayer::new_for_http()) 475 | .with_state(state); 476 | let listener = tokio::net::TcpListener::bind(&args.listen_address) 477 | .await 478 | .with_context(|| format!("opening listen socket on {}", &args.listen_address))?; 479 | axum::serve::serve(listener, app.into_make_service()).await?; 480 | Ok(ExitCode::SUCCESS) 481 | } 482 | } 483 | -------------------------------------------------------------------------------- /tests/test.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: 2023 Guillaume Girol 2 | // 3 | // SPDX-License-Identifier: GPL-3.0-only 4 | 5 | use assert_cmd::assert::Assert; 6 | use assert_cmd::prelude::*; 7 | use std::fs::OpenOptions; 8 | use std::io::{Seek, SeekFrom, Write}; 9 | use std::os::unix::fs::OpenOptionsExt; 10 | use std::os::unix::prelude::OsStrExt; 11 | use std::path::Path; 12 | use std::process::{Command, Stdio}; 13 | use std::{os::unix::process::CommandExt, path::PathBuf}; 14 | use tempfile::TempDir; 15 | 16 | fn nixseparatedebuginfod(t: &TempDir) -> Command { 17 | let mut cmd = Command::cargo_bin("nixseparatedebuginfod").unwrap(); 18 | cmd.env("XDG_CACHE_HOME", t.path()); 19 | cmd 20 | } 21 | 22 | /// Blocks until nixseparatedebuginfod has scanned all of the store 23 | fn populate_cache(t: &TempDir) { 24 | let mut cmd = nixseparatedebuginfod(t); 25 | cmd.arg("-i"); 26 | cmd.env("RUST_LOG", "debug"); 27 | dbg!(cmd).assert().success(); 28 | } 29 | 30 | fn wait_for_port(port: u16) { 31 | while let Err(e) = reqwest::blocking::get(&format!("http://127.0.0.1:{port}")) { 32 | println!("port {} is not open yet: {:#}", port, e); 33 | std::thread::sleep(std::time::Duration::from_secs(1)); 34 | } 35 | } 36 | 37 | fn which(cmd: &str) -> String { 38 | String::from_utf8_lossy( 39 | &Command::new("sh") 40 | .arg("-c") 41 | .arg(format!("command -v {cmd}")) 42 | .assert() 43 | .get_output() 44 | .stdout, 45 | ) 46 | .trim_end() 47 | .to_owned() 48 | } 49 | 50 | /// Spawns a nixseparatedebuginfod on a random port 51 | /// 52 | /// returns the port and child handle. Don't forget to kill it. 53 | /// 54 | /// If substituters is not None, hacks the environment so that nix show-config 55 | /// lists those substituters but nix-store commands are not affected. 56 | fn spawn_server(t: &TempDir, substituters: Option>) -> (u16, std::process::Child) { 57 | let port: u16 = 3000 + rand::random::() as u16; 58 | let mut cmd = nixseparatedebuginfod(t); 59 | cmd.arg("-l"); 60 | cmd.arg(format!("127.0.0.1:{port}")); 61 | suicide(&mut cmd); 62 | if let Some(substituters) = substituters { 63 | let current_nix = dbg!(which("nix")); 64 | let sh = dbg!(which("sh")); 65 | let nix_conf = file_in(t, "nix.conf"); 66 | let substituters_as_str = &substituters.join(" "); 67 | std::fs::write(nix_conf, format!("substituters = {substituters_as_str}\ntrusted-substituters = {substituters_as_str}\n")).unwrap(); 68 | let fake_bin = t.path().join(format!("fakebin{port}")); 69 | std::fs::create_dir_all(&fake_bin).unwrap(); 70 | let fake_nix = fake_bin.join("nix"); 71 | let mut fd = OpenOptions::new() 72 | .create(true) 73 | .truncate(true) 74 | .write(true) 75 | .mode(0o750) 76 | .open(fake_nix) 77 | .unwrap(); 78 | let nix_conf_dir = t.path().display().to_string(); 79 | write!( 80 | &mut fd, 81 | "#!{sh}\nexport NIX_CONF_DIR='{nix_conf_dir}'\nexec {current_nix} \"$@\"\n" 82 | ) 83 | .unwrap(); 84 | cmd.env( 85 | "PATH", 86 | format!( 87 | "{}:{}", 88 | fake_bin.to_string_lossy().as_ref(), 89 | std::env::var("PATH").unwrap() 90 | ), 91 | ); 92 | } 93 | cmd.env( 94 | "RUST_LOG", 95 | "nixseparatedebuginfod=debug,actix=info,sqlx=warn,warn", 96 | ); 97 | let handle = dbg!(cmd).spawn().unwrap(); 98 | wait_for_port(port); 99 | (port, handle) 100 | } 101 | 102 | /// Makes a PathBuf of a file in this directory 103 | fn file_in(t: &TempDir, name: &str) -> PathBuf { 104 | let mut root = t.path().to_path_buf(); 105 | root.push(name); 106 | root 107 | } 108 | 109 | // Runs gdb on this exe with these commands and configured to use debuginfod on this port 110 | // 111 | // Returns its output 112 | fn gdb(t: &TempDir, exe: &Path, port: u16, commands: &str) -> String { 113 | let mut cmd = Command::new("gdb"); 114 | cmd.env("HOME", t.path()); 115 | cmd.env("XDG_CACHE_HOME", t.path()); 116 | cmd.env("NIX_DEBUG_INFO_DIRS", ""); 117 | cmd.env("DEBUGINFOD_URLS", format!("http://127.0.0.1:{port}")); 118 | cmd.env("DEBUGINFOD_VERBOSE", "1"); 119 | let tmpfile = file_in(t, "gdb"); 120 | std::fs::write(&tmpfile, commands).unwrap(); 121 | cmd.arg(exe); 122 | cmd.arg("--batch"); 123 | cmd.arg("--init-eval-command=set debuginfod verbose 10"); 124 | cmd.arg("--init-eval-command=set debuginfod enabled on"); 125 | cmd.arg("-n"); 126 | cmd.arg("-x"); 127 | cmd.arg(&tmpfile); 128 | let output = dbg!(cmd).output().unwrap(); 129 | String::from_utf8_lossy(&output.stdout).to_string() 130 | } 131 | 132 | /// Marks a command to die when its parent (us) die. 133 | fn suicide(cmd: &mut Command) { 134 | unsafe { 135 | cmd.pre_exec(|| prctl::set_death_signal(9).map_err(std::io::Error::from_raw_os_error)); 136 | } 137 | } 138 | 139 | /// Finds a file by name in the tests folder of the repo 140 | fn fixture(name: &str) -> PathBuf { 141 | let mut root = std::env::current_dir().unwrap(); 142 | root.push("tests"); 143 | root.push(name); 144 | root 145 | } 146 | 147 | /// runs nix-build ./tests/debugees.nix -A $attr -o $output --store $store 148 | fn nix_build(attr: &str, output: &Path, store: Option>) { 149 | let mut cmd = Command::new("nix-build"); 150 | cmd.arg(fixture("debugees.nix")); 151 | cmd.arg("-A"); 152 | cmd.arg(attr); 153 | cmd.arg("-o"); 154 | cmd.arg(output); 155 | if let Some(store) = store { 156 | cmd.arg("--store"); 157 | cmd.arg(store.as_ref()); 158 | } 159 | dbg!(cmd).assert().success(); 160 | } 161 | 162 | /// runs nix-instantiate ./tests/debugees.nix -A $attr 163 | fn nix_instantiate(attr: &str) -> PathBuf { 164 | let mut cmd = Command::new("nix-instantiate"); 165 | cmd.arg(fixture("debugees.nix")); 166 | cmd.arg("-A"); 167 | cmd.arg(attr); 168 | let output = dbg!(cmd).output().unwrap(); 169 | let out = String::from_utf8_lossy(&output.stdout); 170 | let path = PathBuf::from(dbg!(out.trim_matches(&['"', '\n'] as &[_]))); 171 | assert!(path.is_absolute()); 172 | path 173 | } 174 | 175 | /// runs nix copy --from ... --to ... --store ... path 176 | fn nix_copy( 177 | from: Option>, 178 | to: Option>, 179 | path: &Path, 180 | store: Option>, 181 | ) { 182 | let mut cmd = Command::new("nix"); 183 | cmd.arg("copy"); 184 | cmd.args([ 185 | "--extra-experimental-features", 186 | "nix-command", 187 | "--extra-experimental-features", 188 | "flakes", 189 | ]); 190 | if let Some(from) = from { 191 | cmd.arg("--from"); 192 | cmd.arg(from.as_ref()); 193 | } 194 | if let Some(to) = to { 195 | cmd.arg("--to"); 196 | cmd.arg(to.as_ref()); 197 | } 198 | if let Some(store) = store { 199 | cmd.arg("--store"); 200 | cmd.arg(store.as_ref()); 201 | } 202 | cmd.arg(path); 203 | dbg!(cmd).assert().success(); 204 | } 205 | 206 | fn delete_path(storepath: impl AsRef) { 207 | let path = storepath.as_ref(); 208 | 209 | if path.exists() { 210 | // using xargs is a hack https://github.com/NixOS/nix/issues/6141#issuecomment-1476807193 211 | let mut file = tempfile::tempfile().unwrap(); 212 | file.write_all(path.as_os_str().as_bytes()).unwrap(); 213 | file.write_all(b"\n").unwrap(); 214 | file.sync_all().unwrap(); 215 | file.seek(SeekFrom::Start(0)).unwrap(); 216 | let mut cmd = Command::new("xargs"); 217 | cmd.arg("--verbose"); 218 | cmd.arg("nix-store") 219 | .arg("--delete") 220 | .arg("--option") 221 | .arg("auto-optimise-store") 222 | .arg("false"); 223 | cmd.stdin(file); 224 | cmd.stdout(Stdio::inherit()); 225 | dbg!(cmd).assert().success(); 226 | 227 | assert!(!path.exists()); 228 | println!("removed {}", path.display()); 229 | } 230 | } 231 | 232 | fn remove_drv_and_outputs(attr: &str) { 233 | // get drv path 234 | let drv_path = nix_eval_drv_path(attr); 235 | 236 | if !drv_path.exists() { 237 | return; 238 | } 239 | 240 | // get all outputs 241 | let mut cmd = Command::new("nix-store"); 242 | cmd.arg("--query").arg("--outputs").arg(&drv_path); 243 | let out = dbg!(cmd).output().unwrap(); 244 | let out = String::from_utf8_lossy(&out.stdout); 245 | for line in out.lines() { 246 | if line.is_empty() { 247 | continue; 248 | } 249 | let path = Path::new(line); 250 | assert!(path.is_absolute()); 251 | // now remove the output 252 | delete_path(path); 253 | } 254 | 255 | delete_path(&drv_path); 256 | } 257 | 258 | /// obtains the store path of an output without creating the .drv file 259 | fn nix_eval_out_path(attr: &str, output: &str) -> PathBuf { 260 | let mut cmd = Command::new("nix-instantiate"); 261 | cmd.arg("--eval").arg("-E").arg(format!( 262 | "(import {}).{}.{}.outPath", 263 | fixture("debugees.nix").display(), 264 | attr, 265 | output, 266 | )); 267 | let out = dbg!(cmd).output().unwrap(); 268 | let out = String::from_utf8_lossy(&out.stdout); 269 | let path = PathBuf::from(dbg!(out.trim_matches(&['"', '\n'] as &[_]))); 270 | assert!(path.is_absolute()); 271 | path 272 | } 273 | 274 | /// like nix_instantiate but does not create a .drv file 275 | fn nix_eval_drv_path(attr: &str) -> PathBuf { 276 | let mut cmd = Command::new("nix-instantiate"); 277 | cmd.arg("--eval").arg("-E").arg(format!( 278 | "(import {}).{}.drvPath", 279 | fixture("debugees.nix").display(), 280 | attr, 281 | )); 282 | let out = dbg!(cmd).output().unwrap(); 283 | let out = String::from_utf8_lossy(&out.stdout); 284 | let path = PathBuf::from(dbg!(out.trim_matches(&['"', '\n'] as &[_]))); 285 | assert!(path.is_absolute()); 286 | path 287 | } 288 | 289 | fn realise_storepath(storepath: impl AsRef) { 290 | let mut cmd = Command::new("nix-store"); 291 | cmd.arg("--realise").arg(storepath.as_ref()); 292 | dbg!(cmd).assert().success(); 293 | } 294 | 295 | fn remove_debug_output(attr: &str) { 296 | let path = nix_eval_out_path(attr, "debug"); 297 | delete_path(path); 298 | } 299 | 300 | fn remove_debuginfo_for_buildid(buildid: &str) { 301 | let segment = format!( 302 | "lib/debug/.build-id/{}/{}.debug", 303 | &buildid[..2], 304 | &buildid[2..] 305 | ); 306 | for entry in std::fs::read_dir("/nix/store").unwrap() { 307 | let entry = entry.unwrap(); 308 | let path = entry.path().join(&segment); 309 | delete_path(&path); 310 | } 311 | } 312 | 313 | #[test] 314 | fn test_normal() { 315 | let t = tempfile::tempdir().unwrap(); 316 | 317 | // gnumake has source in tar.gz files 318 | let output = file_in(&t, "gnumake"); 319 | nix_build("gnumake", &output, None::); 320 | 321 | remove_debug_output("gnumake"); 322 | 323 | let (port, mut server) = spawn_server(&t, Some(vec![])); 324 | 325 | let mut exe = output; 326 | exe.push("bin"); 327 | exe.push("make"); 328 | // this is before indexation finished, and should not populate the client cache 329 | gdb(&t, &exe, port, "start\nl\n"); 330 | 331 | server.kill().unwrap(); 332 | 333 | populate_cache(&t); 334 | 335 | let (port, mut server) = spawn_server(&t, Some(vec![])); 336 | 337 | let out = gdb(&t, &exe, port, "start\nl\n"); 338 | assert!(dbg!(out).contains("1051\tmain (int argc, char **argv)")); 339 | 340 | // nix has source in flat files 341 | let output: PathBuf = file_in(&t, "nixstorepath"); 342 | nix_build("nix", &output, None::); 343 | // we will test fetching the source of a template instantiation from a header-only library 344 | // disabled until nix bin output drops its reference to nlohmann_json 345 | /* 346 | let nlohmann_json = nix_eval_out_path("nlohmann_json", "out"); 347 | delete_path(&nlohmann_json); 348 | */ 349 | 350 | let mut exe = output; 351 | exe.push("bin"); 352 | exe.push("nix"); 353 | // test that gdb can show the source of main (in nix) 354 | // and the source of an inlined template (from nlohmann_json) 355 | let out = gdb( 356 | &t, 357 | &exe, 358 | port, 359 | "start\nl\nn\nl\nl nlohmann::detail::output_stream_adapter::write_character(char)\n", 360 | ); 361 | // gdb fetched the source of main() 362 | assert!(dbg!(&out).contains("389\tint main(int argc, char * * argv)")); 363 | // and fetched the source of a template instantiation in a header-only lib 364 | assert!(out.contains("73\t void write_character(CharType c) override")); 365 | 366 | server.kill().unwrap(); 367 | } 368 | 369 | #[test] 370 | fn test_invalid_deriver() { 371 | let t = tempfile::tempdir().unwrap(); 372 | 373 | // check that nix supports --query --valid-derivers 374 | let mut cmd = Command::new("nix-store"); 375 | cmd.arg("--query").arg("--valid-derivers"); 376 | if !dbg!(cmd.status()).unwrap().success() { 377 | println!("skipping test_invalid_deriver, nix is too old"); 378 | return; 379 | } 380 | 381 | remove_drv_and_outputs("mailutils_drvhash1"); 382 | remove_drv_and_outputs("mailutils_drvhash2"); 383 | 384 | let outpath = nix_eval_out_path("mailutils_drvhash1", "out"); 385 | realise_storepath(&outpath); 386 | 387 | // outpath has a missing deriver 388 | // let's create a different one 389 | nix_instantiate("mailutils_drvhash2"); 390 | 391 | populate_cache(&t); 392 | 393 | // start a server that can't fetch from hydra 394 | let (port, mut server) = spawn_server(&t, Some(vec![])); 395 | 396 | // check that the server can use the deriver of mailutils_drvhash2 instead of 397 | // the deriver returned by hydra (mailutils_drvhash1) 398 | let out = gdb( 399 | &t, 400 | outpath.join("bin/mailutils").as_ref(), 401 | port, 402 | "start\nl\n", 403 | ); 404 | assert!(dbg!(out).contains("156\tmain (int argc, char **argv)")); 405 | 406 | server.kill().unwrap(); 407 | } 408 | 409 | #[test] 410 | fn test_hydra_api_file() { 411 | remove_debuginfo_for_buildid("10deef1d1c1e79a27c25e9636d652ca3b99dc3f5"); 412 | let t = tempfile::tempdir().unwrap(); 413 | let store = file_in(&t, "store"); 414 | 415 | let output = file_in(&t, "python"); 416 | // build in another store so we don't have the drv file 417 | nix_build("python3", &output, Some(&store)); 418 | let python = std::fs::read_link(output).unwrap(); 419 | let output = file_in(&t, "python_debug"); 420 | nix_build("python3.debug", &output, Some(&store)); 421 | let real_output = output.with_file_name(format!( 422 | "{}-debug", 423 | output.file_name().unwrap().to_str().unwrap() 424 | )); 425 | let python_debug = std::fs::read_link(real_output).unwrap(); 426 | 427 | let cache_dir = file_in(&t, "cache"); 428 | let cache = format!("file://{}?index-debug-info=true", cache_dir.display()); 429 | 430 | nix_copy(None::, Some(&cache), &python_debug, Some(&store)); 431 | nix_copy(Some(&store), None::, &python, None::); 432 | 433 | let (port, mut server) = spawn_server(&t, Some(vec![&cache])); 434 | 435 | let exe = python.join("bin/python"); 436 | // this is before indexation finished, and should not populate the client cache 437 | let out = gdb(&t, &exe, port, "start\n"); 438 | // we don't get source code but at least we get location information 439 | assert!(dbg!(out).contains(" at Programs/python.c:15")); 440 | 441 | server.kill().unwrap(); 442 | } 443 | 444 | #[test] 445 | fn test_hydra_api_https() { 446 | remove_debuginfo_for_buildid("78218dee9fd3709104f6521a2c5507fb0a5732b2"); 447 | let t = tempfile::tempdir().unwrap(); 448 | let store = file_in(&t, "store"); 449 | 450 | let output = file_in(&t, "python"); 451 | // build in another store so we don't have the drv file 452 | nix_build("python310", &output, Some(&store)); 453 | let python = std::fs::read_link(output).unwrap(); 454 | 455 | nix_copy(Some(&store), None::, &python, None::); 456 | 457 | let (port, mut server) = spawn_server(&t, None); 458 | 459 | let exe = python.join("bin/python"); 460 | // this is before indexation finished, and should not populate the client cache 461 | let out = gdb(&t, &exe, port, "start\n"); 462 | // we don't get source code but at least we get location information 463 | assert!(dbg!(out).contains(" at Programs/python.c:15")); 464 | 465 | server.kill().unwrap(); 466 | } 467 | 468 | #[test] 469 | fn test_cache_invalidation() { 470 | let t = tempfile::tempdir().unwrap(); 471 | 472 | let output = file_in(&t, "sl"); 473 | nix_build("sl", &output, None::); 474 | let sl = std::fs::read_link(output).unwrap(); 475 | let output = file_in(&t, "sl_debug"); 476 | nix_build("sl.debug", &output, None::); 477 | let real_output = output.with_file_name(format!( 478 | "{}-debug", 479 | output.file_name().unwrap().to_str().unwrap() 480 | )); 481 | let sl_debug = std::fs::read_link(&real_output).unwrap(); 482 | std::fs::remove_file(real_output).unwrap(); 483 | 484 | let cache_dir = file_in(&t, "cache"); 485 | let cache = format!("file://{}?index-debug-info=true", cache_dir.display()); 486 | 487 | nix_copy(None::, Some(&cache), &sl_debug, None::); 488 | 489 | // register the debug output 490 | populate_cache(&t); 491 | 492 | // invalidate the value in the cache 493 | remove_debug_output("sl"); 494 | 495 | let (port, mut server) = spawn_server(&t, Some(vec![&cache])); 496 | 497 | let exe = sl.join("bin/sl"); 498 | // the cached value does not exist anymore and cannot be recreated 499 | // with nix-store --realise, so fetch it with the hydra api 500 | let out = gdb(&t, &exe, port, "start\n"); 501 | assert!(dbg!(out).contains("at sl.c:120")); 502 | 503 | server.kill().unwrap(); 504 | } 505 | 506 | fn fetch_source_from_server(port: u16, exe: impl AsRef, path: impl AsRef) -> Assert { 507 | let t = tempfile::tempdir().unwrap(); 508 | let mut cmd = Command::new("debuginfod-find"); 509 | cmd.arg("source") 510 | .arg(exe.as_ref()) 511 | .arg(path.as_ref()) 512 | .env("XDG_CACHE_HOME", t.path()) 513 | .env("HOME", t.path()) 514 | .env("DEBUGINFOD_URLS", format!("http://localhost:{port}")); 515 | dbg!(cmd).assert() 516 | } 517 | 518 | #[test] 519 | fn test_path_traversal() { 520 | let t = tempfile::tempdir().unwrap(); 521 | 522 | // gnumake has source in tar.gz files 523 | let output = file_in(&t, "rpm"); 524 | nix_build("rpm", &output, None::); 525 | populate_cache(&t); 526 | 527 | let (port, mut server) = spawn_server(&t, Some(vec![])); 528 | 529 | let exe = output.join("bin").join("rpm").canonicalize().unwrap(); 530 | 531 | let test_file = file_in(&t, "target"); 532 | std::fs::write(&test_file, "hi").unwrap(); 533 | 534 | // the server should serve any file in the store 535 | fetch_source_from_server(port, &exe, &exe).success(); 536 | // but not files outside of it 537 | fetch_source_from_server( 538 | port, 539 | &exe, 540 | exe.parent() 541 | .unwrap() 542 | .join(format!("../../../../{}", test_file.to_string_lossy())), 543 | ) 544 | .failure(); 545 | 546 | server.kill().unwrap(); 547 | } 548 | -------------------------------------------------------------------------------- /src/store.rs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: 2023 Guillaume Girol 2 | // 3 | // SPDX-License-Identifier: GPL-3.0-only 4 | 5 | //! Lower level utilities to query the store. 6 | 7 | use crate::db::Entry; 8 | use crate::log::ResultExt; 9 | use anyhow::Context; 10 | use object::read::Object; 11 | use once_cell::unsync::Lazy; 12 | use std::{ 13 | ffi::{OsStr, OsString}, 14 | os::unix::prelude::{OsStrExt, OsStringExt}, 15 | path::{Path, PathBuf}, 16 | sync::atomic::{AtomicBool, Ordering}, 17 | }; 18 | use tokio::sync::mpsc::Sender; 19 | 20 | /// Whether nix-store supports --query --valid-derivers (>= 2.18) 21 | /// 22 | /// Set by [detect_nix]. 23 | static NIX_STORE_QUERY_VALID_DERIVERS_SUPPORTED: AtomicBool = AtomicBool::new(false); 24 | 25 | const NIX_STORE: &str = "/nix/store"; 26 | 27 | /// Opens the specified file read only, but only if it's in /nix/store 28 | pub fn open_store_path(path: impl AsRef) -> anyhow::Result { 29 | let Ok(relative) = path.as_ref().strip_prefix(NIX_STORE) else { 30 | anyhow::bail!("{:?} is not a store path", path.as_ref()); 31 | }; 32 | let root = pathrs::Root::open(NIX_STORE).context("opening /nix/store")?; 33 | let path = path.as_ref(); 34 | let handle = root 35 | .resolve(Path::new("/").join(relative)) 36 | .with_context(|| format!("failed to resolve store path {path:?}"))?; 37 | handle 38 | .reopen(pathrs::flags::OpenFlags::O_RDONLY) 39 | .with_context(|| format!("opening store path {path:?}")) 40 | } 41 | /// attempts have this store path exist in the store 42 | /// 43 | /// if the path already exists, do nothing 44 | /// otherwise runs `nix-store --realise` to download it from a binary cache. 45 | pub async fn realise(path: &Path) -> anyhow::Result<()> { 46 | use tokio::fs::metadata; 47 | use tokio::process::Command; 48 | if metadata(path).await.is_ok() { 49 | return Ok(()); 50 | }; 51 | let mut command = Command::new("nix-store"); 52 | command.arg("--realise").arg(path); 53 | tracing::info!("Running {:?}", &command); 54 | let _ = command.status().await; 55 | if metadata(path).await.is_ok() { 56 | return Ok(()); 57 | }; 58 | anyhow::bail!("nix-store --realise {} failed", path.display()); 59 | } 60 | 61 | /// downloads a .drv file if necessary 62 | /// 63 | /// if the path already exists, do nothing 64 | /// otherwise runs `nix-store --realise` to download it from a binary cache. 65 | fn download_drv(path: &Path) -> anyhow::Result<()> { 66 | use std::fs::metadata; 67 | use std::process::Command; 68 | if metadata(path).is_ok() { 69 | return Ok(()); 70 | }; 71 | let mut command = Command::new("nix-store"); 72 | command.arg("--realise"); 73 | // nix-store --realise foo.drv downloads the drv and its default output 74 | // we use the following trick to only download the drv: we ask for a non existing output 75 | // as the narinfo does not give the list of outputs, nix has to download the drv first, and 76 | // then fails to download the output 77 | command.arg(path.with_extension("drv!outputdoesn0tex1st")); 78 | tracing::info!("Running {:?}", &command); 79 | let _ = command.status(); 80 | if metadata(path).is_ok() { 81 | return Ok(()); 82 | }; 83 | anyhow::bail!("nix-store --realise {} failed", path.display()); 84 | } 85 | 86 | /// Walks a store path and attempts to register everything that has a buildid in it. 87 | /// If offline is false, may try to download the .drv file from cache. 88 | pub fn index_store_path(storepath: &Path, sendto: Sender, offline: bool) { 89 | let span = tracing::info_span!("indexing", storepath=%storepath.display()).entered(); 90 | if storepath 91 | .file_name() 92 | .unwrap_or_default() 93 | .as_bytes() 94 | .ends_with(b".drv") 95 | { 96 | return; 97 | } 98 | if !storepath.is_dir() { 99 | return; 100 | } 101 | let deriver_source = Lazy::new(|| match get_deriver(storepath) { 102 | Err(e) => { 103 | tracing::warn!("no deriver for {}: {:#}", storepath.display(), e); 104 | (None, None) 105 | } 106 | Ok(None) => (None, None), 107 | Ok(Some(deriver)) => { 108 | if !offline && !deriver.is_file() { 109 | download_drv(deriver.as_ref()) 110 | .with_context(|| { 111 | format!( 112 | "downloading deriver {} of {}", 113 | deriver.display(), 114 | storepath.display() 115 | ) 116 | }) 117 | .or_warn(); 118 | } 119 | if deriver.is_file() { 120 | let source = match get_source(deriver.as_path()) { 121 | Err(e) => { 122 | tracing::info!( 123 | "no source for {} (deriver of {}): {:#}", 124 | deriver.display(), 125 | storepath.display(), 126 | e 127 | ); 128 | None 129 | } 130 | Ok(s) => Some(s), 131 | }; 132 | (Some(deriver), source) 133 | } else { 134 | (None, None) 135 | } 136 | } 137 | }); 138 | let storepath_os: &OsStr = storepath.as_ref(); 139 | if storepath_os.as_bytes().ends_with(b"-debug") { 140 | let mut root = storepath.to_owned(); 141 | root.push("lib"); 142 | root.push("debug"); 143 | root.push(".build-id"); 144 | if !root.is_dir() { 145 | return; 146 | }; 147 | let readroot = match std::fs::read_dir(&root) { 148 | Err(e) => { 149 | tracing::warn!("could not list {}: {:#}", root.display(), e); 150 | return; 151 | } 152 | Ok(r) => r, 153 | }; 154 | for mid in readroot { 155 | let mid = match mid { 156 | Err(e) => { 157 | tracing::warn!("could not list {}: {:#}", root.display(), e); 158 | continue; 159 | } 160 | Ok(mid) => mid, 161 | }; 162 | if !mid.file_type().map(|x| x.is_dir()).unwrap_or(false) { 163 | continue; 164 | }; 165 | let mid_path = mid.path(); 166 | let mid_name_os = mid.file_name(); 167 | let mid_name = match mid_name_os.to_str() { 168 | None => continue, 169 | Some(x) => x, 170 | }; 171 | let read_mid = match std::fs::read_dir(&mid_path) { 172 | Err(e) => { 173 | tracing::warn!("could not list {}: {:#}", mid_path.display(), e); 174 | continue; 175 | } 176 | Ok(r) => r, 177 | }; 178 | for end in read_mid { 179 | let end = match end { 180 | Err(e) => { 181 | tracing::warn!("could not list {}: {:#}", mid_path.display(), e); 182 | continue; 183 | } 184 | Ok(end) => end, 185 | }; 186 | if !end.file_type().map(|x| x.is_file()).unwrap_or(false) { 187 | continue; 188 | }; 189 | let end_name_os = end.file_name(); 190 | let end_name = match end_name_os.to_str() { 191 | None => continue, 192 | Some(x) => x, 193 | }; 194 | if !end_name.ends_with(".debug") { 195 | continue; 196 | }; 197 | let buildid = format!( 198 | "{}{}", 199 | &mid_name, 200 | &end_name[..(end_name.len() - ".debug".len())] 201 | ); 202 | let (_, source) = &*deriver_source; 203 | let entry = Entry { 204 | debuginfo: end.path().to_str().map(|s| s.to_owned()), 205 | executable: None, 206 | source: source.as_ref().and_then(|path| { 207 | path.as_ref() 208 | .and_then(|path| path.to_str()) 209 | .map(|s| s.to_owned()) 210 | }), 211 | buildid, 212 | }; 213 | sendto 214 | .blocking_send(entry) 215 | .context("sending entry failed") 216 | .or_warn(); 217 | } 218 | } 219 | } else { 220 | let debug_output = Lazy::new(|| { 221 | let (deriver, _) = &*deriver_source; 222 | match deriver { 223 | None => None, 224 | Some(deriver) => match get_debug_output(deriver.as_path()) { 225 | Ok(None) => None, 226 | Err(e) => { 227 | tracing::warn!( 228 | "could not determine if the deriver {} of {} has a debug output: {:#}", 229 | storepath.display(), 230 | deriver.display(), 231 | e 232 | ); 233 | None 234 | } 235 | Ok(Some(d)) => Some(d), 236 | }, 237 | } 238 | }); 239 | for file in walkdir::WalkDir::new(storepath) { 240 | let file = match file { 241 | Err(_) => continue, 242 | Ok(file) => file, 243 | }; 244 | if !file.file_type().is_file() { 245 | continue; 246 | }; 247 | let path = file.path(); 248 | let buildid = match get_buildid(path) { 249 | Err(e) => { 250 | tracing::info!("cannot get buildid of {}: {:#}", path.display(), e); 251 | continue; 252 | } 253 | Ok(Some(buildid)) => buildid, 254 | Ok(None) => continue, 255 | }; 256 | let debuginfo = match &*debug_output { 257 | None => None, 258 | Some(storepath) => { 259 | let theoretical = debuginfo_path_for(&buildid, storepath.as_path()); 260 | if storepath.is_dir() { 261 | // the store path is available, check the prediction 262 | if !theoretical.is_file() { 263 | tracing::warn!( 264 | "{} has buildid {}, and {} exists but not {}", 265 | path.display(), 266 | buildid, 267 | storepath.display(), 268 | theoretical.display() 269 | ); 270 | None 271 | } else { 272 | Some(theoretical) 273 | } 274 | } else { 275 | Some(theoretical) 276 | } 277 | } 278 | }; 279 | let (_, source) = &*deriver_source; 280 | let entry = Entry { 281 | buildid, 282 | source: source.as_ref().and_then(|path| { 283 | path.as_ref() 284 | .and_then(|path| path.to_str()) 285 | .map(|s| s.to_owned()) 286 | }), 287 | executable: path.to_str().map(|s| s.to_owned()), 288 | debuginfo: debuginfo.and_then(|path| path.to_str().map(|s| s.to_owned())), 289 | }; 290 | sendto 291 | .blocking_send(entry) 292 | .context("sending entry failed") 293 | .or_warn(); 294 | } 295 | } 296 | drop(span) 297 | } 298 | 299 | /// Return the path where separate debuginfo is to be found in a debug output for a buildid 300 | fn debuginfo_path_for(buildid: &str, debug_output: &Path) -> PathBuf { 301 | let mut res = debug_output.to_path_buf(); 302 | res.push("lib"); 303 | res.push("debug"); 304 | res.push(".build-id"); 305 | res.push(&buildid[..2]); 306 | res.push(format!("{}.debug", &buildid[2..])); 307 | res 308 | } 309 | 310 | /// Obtains the original deriver of a store path. 311 | /// 312 | /// Corresponds to `nix-store --query --deriver` 313 | /// 314 | /// The store path must exist. 315 | fn get_original_deriver(storepath: &Path) -> anyhow::Result> { 316 | let mut cmd = std::process::Command::new("nix-store"); 317 | cmd.arg("--query").arg("--deriver").arg(storepath); 318 | tracing::debug!("Running {:?}", &cmd); 319 | let out = cmd.output().with_context(|| format!("running {:?}", cmd))?; 320 | if !out.status.success() { 321 | anyhow::bail!("{:?} failed: {}", cmd, String::from_utf8_lossy(&out.stderr)); 322 | } 323 | let n = out.stdout.len(); 324 | if n <= 1 || out.stdout[n - 1] != b'\n' { 325 | anyhow::bail!( 326 | "{:?} returned weird output: {}", 327 | cmd, 328 | String::from_utf8_lossy(&out.stderr) 329 | ); 330 | } 331 | let path = PathBuf::from(OsString::from_vec(out.stdout[..n - 1].to_owned())); 332 | if path.as_path() == Path::new("unknown-deriver") { 333 | return Ok(None); 334 | } 335 | if !path.is_absolute() { 336 | // nix returns `unknown-deriver` when it does not know 337 | anyhow::bail!("no deriver: {}", path.display()); 338 | }; 339 | Ok(Some(path)) 340 | } 341 | 342 | /// Obtains a set of local derivers for a store path. 343 | /// 344 | /// Corresponds to `nix-store --query --valid-derivers` 345 | /// 346 | /// The store path must exist. 347 | /// 348 | /// Fails if nix version is < 2.18 349 | fn get_valid_derivers(storepath: &Path) -> anyhow::Result> { 350 | let mut cmd = std::process::Command::new("nix-store"); 351 | cmd.arg("--query").arg("--valid-derivers").arg(storepath); 352 | tracing::debug!("Running {:?}", &cmd); 353 | let out = cmd.output().with_context(|| format!("running {:?}", cmd))?; 354 | if !out.status.success() { 355 | anyhow::bail!("{:?} failed: {}", cmd, String::from_utf8_lossy(&out.stderr)); 356 | } 357 | let mut result = Vec::new(); 358 | for line in out.stdout.split(|&c| c == b'\n') { 359 | if !line.is_empty() { 360 | let path = PathBuf::from(OsString::from_vec(line.to_owned())); 361 | if !path.is_absolute() { 362 | // nix returns `unknown-deriver` when it does not know 363 | anyhow::bail!( 364 | "incorrect deriver {} for {}", 365 | String::from_utf8_lossy(line), 366 | path.display() 367 | ); 368 | }; 369 | result.push(path) 370 | } 371 | } 372 | Ok(result) 373 | } 374 | 375 | /// Attempts to obtain any deriver for this store path, preferably existing. 376 | /// 377 | /// Corresponds to `nix-store --query --deriver` or `nix-store --query --valid-derivers. 378 | /// 379 | /// The store path must exist. 380 | fn get_deriver(storepath: &Path) -> anyhow::Result> { 381 | if NIX_STORE_QUERY_VALID_DERIVERS_SUPPORTED.load(Ordering::SeqCst) { 382 | for path in get_valid_derivers(storepath) 383 | .with_context(|| format!("getting valid deriver for {}", storepath.display()))? 384 | { 385 | if path.exists() { 386 | return Ok(Some(path)); 387 | } else { 388 | tracing::warn!( 389 | "nix-store --query --valid-derivers {} returned a non-existing path", 390 | storepath.display() 391 | ); 392 | } 393 | } 394 | } 395 | get_original_deriver(storepath) 396 | .with_context(|| format!("getting original deriver for {}", storepath.display())) 397 | } 398 | 399 | /// Checks that nix is installed. 400 | /// 401 | /// Also stores in global state whether some features only available in recent nix 402 | /// versions are available. 403 | /// 404 | /// Should be called on startup. 405 | pub fn detect_nix() -> anyhow::Result<()> { 406 | let mut test_path = None; 407 | for entry in Path::new("/nix/store") 408 | .read_dir() 409 | .context("listing directory content of /nix/store")? 410 | { 411 | let entry = entry.context("reading directory entry in /nix/store")?; 412 | if entry.file_name().as_bytes().starts_with(b".") { 413 | continue; 414 | } 415 | test_path = Some(entry.path()); 416 | break; 417 | } 418 | let test_path = match test_path { 419 | Some(test_path) => test_path, 420 | None => anyhow::bail!("/nix/store is empty, did you really install nix?"), 421 | }; 422 | if get_valid_derivers(&test_path).is_ok() { 423 | NIX_STORE_QUERY_VALID_DERIVERS_SUPPORTED.store(true, Ordering::SeqCst); 424 | tracing::info!("detected nix >= 2.18"); 425 | return Ok(()); 426 | } 427 | let _ = get_original_deriver(&test_path).with_context(|| { 428 | format!( 429 | "checking nix install by getting deriver of {}", 430 | test_path.display() 431 | ) 432 | })?; 433 | tracing::warn!("detected nix < 2.18, a more recent nix is required to obtain source files in some situations."); 434 | Ok(()) 435 | } 436 | 437 | /// Obtains the debug output corresponding to this derivation 438 | /// 439 | /// The derivation must exist. 440 | fn get_debug_output(drvpath: &Path) -> anyhow::Result> { 441 | let mut cmd = std::process::Command::new("nix-store"); 442 | cmd.arg("--query").arg("--outputs").arg(drvpath); 443 | tracing::debug!("Running {:?}", &cmd); 444 | let out = cmd.output().with_context(|| format!("running {:?}", cmd))?; 445 | if !out.status.success() { 446 | anyhow::bail!("{:?} failed: {}", cmd, String::from_utf8_lossy(&out.stderr)); 447 | } 448 | for output in out.stdout.split(|&elt| elt == b'\n') { 449 | if output.ends_with(b"-debug") { 450 | return Ok(Some(PathBuf::from(OsString::from_vec(output.to_owned())))); 451 | } 452 | } 453 | Ok(None) 454 | } 455 | 456 | /// Obtains the source store path corresponding to this derivation 457 | /// 458 | /// The derivation must exist. 459 | /// 460 | /// Source is understood as `src = `, multiple sources or patches are not supported. 461 | fn get_source(drvpath: &Path) -> anyhow::Result> { 462 | let mut cmd = std::process::Command::new("nix-store"); 463 | cmd.arg("--query").arg("--binding").arg("src").arg(drvpath); 464 | tracing::debug!("Running {:?}", &cmd); 465 | let out = cmd.output().with_context(|| format!("running {:?}", cmd))?; 466 | if !out.status.success() { 467 | if out 468 | .stderr 469 | .as_slice() 470 | .ends_with(b"has no environment binding named 'src'\n") 471 | { 472 | return Ok(None); 473 | } else { 474 | anyhow::bail!("{:?} failed: {}", cmd, String::from_utf8_lossy(&out.stderr)); 475 | } 476 | } 477 | let n = out.stdout.len(); 478 | if n <= 1 || out.stdout[n - 1] != b'\n' { 479 | anyhow::bail!( 480 | "{:?} returned weird output: {}", 481 | cmd, 482 | String::from_utf8_lossy(&out.stderr) 483 | ); 484 | } 485 | let path = PathBuf::from(OsString::from_vec(out.stdout[..n - 1].to_owned())); 486 | if !path.is_absolute() { 487 | anyhow::bail!("weird source: {}", path.display()); 488 | }; 489 | Ok(Some(path)) 490 | } 491 | 492 | /// Where a source file might be 493 | #[derive(Debug, Clone, PartialEq, Eq)] 494 | pub enum SourceLocation { 495 | /// Inside an archive 496 | Archive { 497 | /// path of the archive 498 | archive: PathBuf, 499 | /// path of the file in the archive 500 | member: PathBuf, 501 | }, 502 | /// A file directly in the store 503 | File(PathBuf), 504 | } 505 | 506 | impl SourceLocation { 507 | /// Get the path against which we match the requested file name 508 | fn member_path(&self) -> &Path { 509 | match self { 510 | SourceLocation::Archive { member, .. } => member.as_path(), 511 | SourceLocation::File(path) => path.as_path(), 512 | } 513 | } 514 | } 515 | 516 | /// Return the build id of this file. 517 | /// 518 | /// If the file is not an executable returns Ok(None). 519 | /// Errors are only for errors returned from the fs. 520 | pub fn get_buildid(path: &Path) -> anyhow::Result> { 521 | let file = std::fs::File::open(path) 522 | .with_context(|| format!("opening {} to get its buildid", path.display()))?; 523 | let reader = object::read::ReadCache::new(file); 524 | let object = match object::read::File::parse(&reader) { 525 | Err(_) => { 526 | // object::read::Error is opaque, so no way to distinguish "this is not elf" and a real 527 | // error 528 | return Ok(None); 529 | } 530 | Ok(o) => o, 531 | }; 532 | match object 533 | .build_id() 534 | .with_context(|| format!("parsing {} for buildid", path.display()))? 535 | { 536 | None => Ok(None), 537 | Some(data) => { 538 | let buildid = base16::encode_lower(&data); 539 | Ok(Some(buildid)) 540 | } 541 | } 542 | } 543 | 544 | /// To remove references, gcc is patched to replace the hash part 545 | /// of store path by an uppercase version in debug symbols. 546 | /// 547 | /// Store paths are embedded in debug symbols for example as the location 548 | /// of template instantiation from libraries that live in other derivations. 549 | /// 550 | /// This function undoes the mangling. 551 | pub fn demangle(storepath: PathBuf) -> PathBuf { 552 | if !storepath.starts_with(NIX_STORE) { 553 | return storepath; 554 | } 555 | let mut as_bytes = storepath.into_os_string().into_vec(); 556 | let len = as_bytes.len(); 557 | let store_len = NIX_STORE.len(); 558 | as_bytes[len.min(store_len + 1)..len.min(store_len + 1 + 32)].make_ascii_lowercase(); 559 | OsString::from_vec(as_bytes).into() 560 | } 561 | 562 | #[test] 563 | fn test_demangle_nominal() { 564 | assert_eq!(demangle(PathBuf::from("/nix/store/JW65XNML1FGF4BFGZGISZCK3LFJWXG6L-GCC-12.3.0/include/c++/12.3.0/bits/vector.tcc")), PathBuf::from("/nix/store/jw65xnml1fgf4bfgzgiszck3lfjwxg6l-GCC-12.3.0/include/c++/12.3.0/bits/vector.tcc")); 565 | } 566 | 567 | #[test] 568 | fn test_demangle_noop() { 569 | assert_eq!(demangle(PathBuf::from("/nix/store/jw65xnml1fgf4bfgzgiszck3lfjwxg6l-gcc-12.3.0/include/c++/12.3.0/bits/vector.tcc")), PathBuf::from("/nix/store/jw65xnml1fgf4bfgzgiszck3lfjwxg6l-gcc-12.3.0/include/c++/12.3.0/bits/vector.tcc")); 570 | } 571 | 572 | #[test] 573 | fn test_demangle_empty() { 574 | assert_eq!(demangle(PathBuf::from("/")), PathBuf::from("/")); 575 | } 576 | 577 | #[test] 578 | fn test_demangle_incomplete() { 579 | assert_eq!( 580 | demangle(PathBuf::from("/nix/store/JW65XNML1FGF4B")), 581 | PathBuf::from("/nix/store/jw65xnml1fgf4b") 582 | ); 583 | } 584 | 585 | #[test] 586 | fn test_demangle_non_storepath() { 587 | assert_eq!( 588 | demangle(PathBuf::from("/build/src/FOO.C")), 589 | PathBuf::from("/build/src/FOO.C") 590 | ); 591 | } 592 | 593 | /// Attempts to find a file that matches the request in an existing source path. 594 | pub fn get_file_for_source( 595 | source: &Path, 596 | request: &Path, 597 | ) -> anyhow::Result> { 598 | tracing::info!( 599 | "request path {:?} in source {:?}", 600 | request.display(), 601 | source.display() 602 | ); 603 | 604 | let target: Vec<&OsStr> = request.iter().collect(); 605 | // invariant: we only keep candidates which have same path as target for components i.. 606 | let mut candidates: Vec<_> = Vec::new(); 607 | let source_type = source 608 | .metadata() 609 | .with_context(|| format!("stat({})", source.display()))?; 610 | if source_type.is_dir() { 611 | for file in walkdir::WalkDir::new(source) { 612 | match file { 613 | Err(e) => { 614 | tracing::warn!("failed to walk source {}: {:#}", source.display(), e); 615 | continue; 616 | } 617 | Ok(f) => { 618 | if Some(&f.file_name()) == target.last() { 619 | candidates.push(SourceLocation::File(f.path().to_path_buf())); 620 | } 621 | } 622 | } 623 | } 624 | } else if source_type.is_file() { 625 | let mut archive = std::fs::File::open(source) 626 | .with_context(|| format!("opening source archive {}", source.display()))?; 627 | let member_list = compress_tools::list_archive_files(&mut archive) 628 | .with_context(|| format!("listing files in source archive {}", source.display()))?; 629 | for member in member_list { 630 | if Path::new(&member).file_name().as_ref() == target.last() { 631 | candidates.push(SourceLocation::Archive { 632 | archive: source.to_path_buf(), 633 | member: PathBuf::from(member), 634 | }); 635 | } 636 | } 637 | } 638 | if candidates.len() < 2 { 639 | return Ok(candidates.pop()); 640 | } 641 | let mut best_total_len = 0; 642 | let mut best_matching_len = 0; 643 | let mut best_candidates = Vec::new(); 644 | for candidate in candidates { 645 | let member_path = candidate.member_path(); 646 | let total_len = member_path.iter().count(); 647 | let matching_len = member_path 648 | .iter() 649 | .rev() 650 | .zip(target.iter().rev()) 651 | .skip(1) 652 | .position(|(ref c, t)| c != t) 653 | .unwrap_or(total_len - 1); 654 | if matching_len > best_matching_len 655 | || (matching_len == best_matching_len && total_len < best_total_len) 656 | { 657 | best_matching_len = matching_len; 658 | best_total_len = total_len; 659 | best_candidates.clear(); 660 | best_candidates.push(candidate); 661 | } else if matching_len == best_matching_len { 662 | best_candidates.push(candidate); 663 | } 664 | } 665 | if best_candidates.len() > 1 { 666 | anyhow::bail!( 667 | "cannot tell {:?} apart from {} for target {}", 668 | &best_candidates, 669 | &source.display(), 670 | request.display() 671 | ); 672 | } 673 | Ok(best_candidates.pop()) 674 | } 675 | 676 | #[cfg(test)] 677 | fn make_test_source_path(paths: Vec<&'static str>) -> tempfile::TempDir { 678 | let dir = tempfile::TempDir::new().unwrap(); 679 | for path in paths { 680 | let path = dir.path().join(path); 681 | std::fs::create_dir_all(path.parent().unwrap()).unwrap(); 682 | std::fs::write(&path, "content").unwrap(); 683 | } 684 | dir 685 | } 686 | 687 | #[test] 688 | fn get_file_for_source_simple() { 689 | let dir = make_test_source_path(vec!["soft-version/src/main.c", "soft-version/src/Makefile"]); 690 | let res = get_file_for_source(dir.path(), "/source/soft-version/src/main.c".as_ref()) 691 | .unwrap() 692 | .unwrap(); 693 | assert_eq!( 694 | res, 695 | SourceLocation::File(dir.path().join("soft-version/src/main.c")) 696 | ); 697 | } 698 | 699 | #[test] 700 | fn get_file_for_source_different_dir() { 701 | let dir = make_test_source_path(vec!["lib/core-net/network.c", "lib/plat/optee/network.c"]); 702 | let res = get_file_for_source(dir.path(), "/build/source/lib/core-net/network.c".as_ref()) 703 | .unwrap() 704 | .unwrap(); 705 | assert_eq!( 706 | res, 707 | SourceLocation::File(dir.path().join("lib/core-net/network.c")) 708 | ); 709 | } 710 | 711 | #[test] 712 | fn get_file_for_source_regression_pr_7() { 713 | let dir = make_test_source_path(vec![ 714 | "store/source/lib/core-net/network.c", 715 | "store/source/lib/plat/optee/network.c", 716 | ]); 717 | let res = get_file_for_source(dir.path(), "build/source/lib/core-net/network.c".as_ref()) 718 | .unwrap() 719 | .unwrap(); 720 | assert_eq!( 721 | res, 722 | SourceLocation::File(dir.path().join("store/source/lib/core-net/network.c")) 723 | ); 724 | } 725 | 726 | #[test] 727 | fn get_file_for_source_no_right_filename() { 728 | let dir = make_test_source_path(vec![ 729 | "store/source/lib/core-net/network.c", 730 | "store/source/lib/plat/optee/network.c", 731 | ]); 732 | let res = get_file_for_source( 733 | dir.path(), 734 | "build/source/lib/core-net/somethingelse.c".as_ref(), 735 | ); 736 | assert_eq!(res.unwrap(), None); 737 | } 738 | 739 | #[test] 740 | fn get_file_for_source_glibc() { 741 | let dir = make_test_source_path(vec![ 742 | "glibc-2.37/sysdeps/unix/sysv/linux/openat64.c", 743 | "glibc-2.37/sysdeps/mach/hurd/openat64.c", 744 | "glibc-2.37/io/openat64.c", 745 | ]); 746 | let res = get_file_for_source( 747 | dir.path(), 748 | "/build/glibc-2.37/io/../sysdeps/unix/sysv/linux/openat64.c".as_ref(), 749 | ); 750 | assert_eq!( 751 | res.unwrap().unwrap(), 752 | SourceLocation::File( 753 | dir.path() 754 | .join("glibc-2.37/sysdeps/unix/sysv/linux/openat64.c") 755 | ) 756 | ); 757 | } 758 | 759 | #[test] 760 | fn get_file_for_source_misleading_dir() { 761 | let dir = make_test_source_path(vec!["store/store/wrong/dir/file", "good/dir/store/file"]); 762 | let res = get_file_for_source(dir.path(), "/build/project/store/file".as_ref()); 763 | assert_eq!( 764 | res.unwrap().unwrap(), 765 | SourceLocation::File(dir.path().join("good/dir/store/file")) 766 | ); 767 | } 768 | 769 | #[test] 770 | fn get_file_for_source_ambiguous() { 771 | let sources = vec![ 772 | "glibc-2.37/sysdeps/unix/sysv/linux/openat64.c", 773 | "glibc-2.37/sysdeps/mach/hurd/openat64.c", 774 | "glibc-2.37/io/openat64.c", 775 | ]; 776 | let dir = make_test_source_path(sources.clone()); 777 | let res = get_file_for_source( 778 | dir.path(), 779 | "/build/glibc-2.37/fakeexample/openat64.c".as_ref(), 780 | ); 781 | assert!(res.is_err()); 782 | let msg = res.unwrap_err().to_string(); 783 | assert!(dbg!(&msg).contains("cannot tell")); 784 | assert!(msg.contains("apart")); 785 | for source in sources { 786 | assert!(msg.contains(source)); 787 | } 788 | } 789 | 790 | /// Turns a path in the store as its topmost parent in /nix/store 791 | pub fn get_store_path(path: &Path) -> Option<&Path> { 792 | let mut ancestors = path.ancestors().peekable(); 793 | while let Some(a) = ancestors.next() { 794 | match ancestors.peek() { 795 | Some(p) if p.as_os_str() == "/nix/store" => return Some(a), 796 | _ => (), 797 | } 798 | } 799 | None 800 | } 801 | 802 | #[test] 803 | fn test_get_store_path() { 804 | assert_eq!( 805 | get_store_path(Path::new("/nix/store/foo")).unwrap(), 806 | Path::new("/nix/store/foo") 807 | ); 808 | assert_eq!( 809 | get_store_path(Path::new("/nix/store/foo/bar")).unwrap(), 810 | Path::new("/nix/store/foo") 811 | ); 812 | assert_eq!(get_store_path(Path::new("eq")), None); 813 | } 814 | -------------------------------------------------------------------------------- /LICENSES/GPL-3.0-only.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright © 2007 Free Software Foundation, Inc. 5 | 6 | Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for software and other kinds of works. 11 | 12 | The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. 13 | 14 | When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. 15 | 16 | To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. 17 | 18 | For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. 19 | 20 | Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. 21 | 22 | For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. 23 | 24 | Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. 25 | 26 | Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. 27 | 28 | The precise terms and conditions for copying, distribution and modification follow. 29 | 30 | TERMS AND CONDITIONS 31 | 32 | 0. Definitions. 33 | 34 | “This License” refers to version 3 of the GNU General Public License. 35 | 36 | “Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. 37 | 38 | “The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations. 39 | 40 | To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work. 41 | 42 | A “covered work” means either the unmodified Program or a work based on the Program. 43 | 44 | To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. 45 | 46 | To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. 47 | 48 | An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 49 | 50 | 1. Source Code. 51 | The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work. 52 | 53 | A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. 54 | 55 | The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. 56 | 57 | The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. 58 | 59 | The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. 60 | 61 | The Corresponding Source for a work in source code form is that same work. 62 | 63 | 2. Basic Permissions. 64 | All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. 65 | 66 | You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. 67 | 68 | Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 69 | 70 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 71 | No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. 72 | 73 | When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 74 | 75 | 4. Conveying Verbatim Copies. 76 | You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. 77 | 78 | You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 79 | 80 | 5. Conveying Modified Source Versions. 81 | You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: 82 | 83 | a) The work must carry prominent notices stating that you modified it, and giving a relevant date. 84 | 85 | b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”. 86 | 87 | c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. 88 | 89 | d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. 90 | 91 | A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 92 | 93 | 6. Conveying Non-Source Forms. 94 | You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: 95 | 96 | a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. 97 | 98 | b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. 99 | 100 | c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. 101 | 102 | d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. 103 | 104 | e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. 105 | 106 | A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. 107 | 108 | A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. 109 | 110 | “Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. 111 | 112 | If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). 113 | 114 | The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. 115 | 116 | Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 117 | 118 | 7. Additional Terms. 119 | “Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. 120 | 121 | When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. 122 | 123 | Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: 124 | 125 | a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or 126 | 127 | b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or 128 | 129 | c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or 130 | 131 | d) Limiting the use for publicity purposes of names of licensors or authors of the material; or 132 | 133 | e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or 134 | 135 | f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. 136 | 137 | All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. 138 | 139 | If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. 140 | 141 | Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 142 | 143 | 8. Termination. 144 | You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). 145 | 146 | However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. 147 | 148 | Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. 149 | 150 | Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 151 | 152 | 9. Acceptance Not Required for Having Copies. 153 | You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 154 | 155 | 10. Automatic Licensing of Downstream Recipients. 156 | Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. 157 | 158 | An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. 159 | 160 | You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 161 | 162 | 11. Patents. 163 | A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”. 164 | 165 | A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. 166 | 167 | Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. 168 | 169 | In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. 170 | 171 | If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. 172 | 173 | If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. 174 | 175 | A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. 176 | 177 | Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 178 | 179 | 12. No Surrender of Others' Freedom. 180 | If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 181 | 182 | 13. Use with the GNU Affero General Public License. 183 | Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 184 | 185 | 14. Revised Versions of this License. 186 | The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. 187 | 188 | Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. 189 | 190 | If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. 191 | 192 | Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 193 | 194 | 15. Disclaimer of Warranty. 195 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 196 | 197 | 16. Limitation of Liability. 198 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 199 | 200 | 17. Interpretation of Sections 15 and 16. 201 | If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. 202 | 203 | END OF TERMS AND CONDITIONS 204 | 205 | How to Apply These Terms to Your New Programs 206 | 207 | If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. 208 | 209 | To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found. 210 | 211 | 212 | Copyright (C) 213 | 214 | This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 215 | 216 | This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 217 | 218 | You should have received a copy of the GNU General Public License along with this program. If not, see . 219 | 220 | Also add information on how to contact you by electronic and paper mail. 221 | 222 | If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: 223 | 224 | Copyright (C) 225 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 226 | This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. 227 | 228 | The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”. 229 | 230 | You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . 231 | 232 | The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . 233 | --------------------------------------------------------------------------------