code:
/* GNU Guix --- Functional package management for GNU
   Copyright (C) 2016, 2017, 2018, 2019 Ludovic Courtès <ludo@gnu.org>

   This file is part of GNU Guix.

   GNU Guix 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.

   GNU Guix 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.

   You should have received a copy of the GNU General Public License
   along with GNU Guix.  If not, see <http://www.gnu.org/licenses/>.  */

#include <builtins.hh>
#include <util.hh>
#include <globals.hh>

#include <unistd.h>
#include <cstdlib>

namespace nix {

static void builtinDownload(const Derivation &drv,
			    const std::string &drvPath,
			    const std::string &output)
{
    /* Invoke 'guix perform-download'.  */
    Strings args;
    args.push_back("perform-download");
    args.push_back(drvPath);

    /* Close all other file descriptors. */
    closeMostFDs(set<int>());

    const char *const argv[] =
      {
	  "guix", "perform-download", drvPath.c_str(), output.c_str(), NULL
      };

    /* Tell the script what the store file name is, so that
       'strip-store-file-name' (used for instance to determine the URL of
       content-addressed mirrors) works correctly.  */
    setenv("NIX_STORE", settings.nixStore.c_str(), 1);

    /* Tell it about options such as "print-extended-build-trace".  */
    setenv("_NIX_OPTIONS", settings.pack().c_str(), 1);

    const string program = settings.guixProgram;
    execv(program.c_str(), (char *const *) argv);

    throw SysError(format("failed to run download program '%1%'") % program);
}

static const std::map<std::string, derivationBuilder> builtins =
{
    { "download", builtinDownload }
};

derivationBuilder lookupBuiltinBuilder(const std::string & name)
{
    if (name.substr(0, 8) == "builtin:")
    {
	auto realName = name.substr(8);
	auto builder = builtins.find(realName);
	return builder == builtins.end() ? NULL : builder->second;
    }
    else
	return NULL;
}

std::list<std::string> builtinBuilderNames()
{
    std::list<std::string> result;
    for(auto&& iter: builtins)
    {
	result.push_back(iter.first);
    }
    return result;
}

}

repo_name: maximed/guix

license: mit


code:
/* GNU Guix --- Functional package management for GNU
   Copyright (C) 2016, 2017 Ludovic Courtès <ludo@gnu.org>

   This file is part of GNU Guix.

   GNU Guix 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.

   GNU Guix 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.

   You should have received a copy of the GNU General Public License
   along with GNU Guix.  If not, see <http://www.gnu.org/licenses/>.  */

/* Interface to built-in derivation builders.  */

#pragma once

#include <derivations.hh>
#include <map>
#include <string>

namespace nix {

    inline bool isBuiltin(const Derivation & drv)
    {
	return string(drv.builder, 0, 8) == "builtin:";
    }

    /* Build DRV, which lives at DRVPATH.  */
    typedef void (*derivationBuilder) (const Derivation &drv,
				       const std::string &drvPath,
				       const std::string &output);

    /* Return the built-in builder called BUILDER, or NULL if none was
       found.  */
    derivationBuilder lookupBuiltinBuilder(const std::string &builder);

    /* Return the list of supported built-in builder names.  */
    std::list<std::string> builtinBuilderNames();
}


code:
#include "derivations.hh"
#include "store-api.hh"
#include "globals.hh"
#include "util.hh"
#include "misc.hh"

namespace nix {

void DerivationOutput::parseHashInfo(bool & recursive, HashType & hashType, Hash & hash) const
{
    recursive = false;
    string algo = hashAlgo;

    if (string(algo, 0, 2) == "r:") {
        recursive = true;
        algo = string(algo, 2);
    }

    hashType = parseHashType(algo);
    if (hashType == htUnknown)
        throw Error(format("unknown hash algorithm `%1%'") % algo);

    hash = parseHash(hashType, this->hash);
}

Path writeDerivation(StoreAPI & store,
    const Derivation & drv, const string & name, bool repair)
{
    PathSet references;
    references.insert(drv.inputSrcs.begin(), drv.inputSrcs.end());
    foreach (DerivationInputs::const_iterator, i, drv.inputDrvs)
        references.insert(i->first);
    /* Note that the outputs of a derivation are *not* references
       (that can be missing (of course) and should not necessarily be
       held during a garbage collection). */
    string suffix = name + drvExtension;
    string contents = unparseDerivation(drv);
    return settings.readOnlyMode
        ? computeStorePathForText(suffix, contents, references)
        : store.addTextToStore(suffix, contents, references, repair);
}

static Path parsePath(std::istream & str)
{
    string s = parseString(str);
    if (s.size() == 0 || s[0] != '/')
        throw FormatError(format("bad path `%1%' in derivation") % s);
    return s;
}

static StringSet parseStrings(std::istream & str, bool arePaths)
{
    StringSet res;
    while (!endOfList(str))
        res.insert(arePaths ? parsePath(str) : parseString(str));
    return res;
}

static Derivation parseDerivation(const string & s)
{
    Derivation drv;
    std::istringstream str(s);
    expect(str, "Derive([");

    /* Parse the list of outputs. */
    while (!endOfList(str)) {
        DerivationOutput out;
        expect(str, "("); string id = parseString(str);
        expect(str, ","); out.path = parsePath(str);
        expect(str, ","); out.hashAlgo = parseString(str);
        expect(str, ","); out.hash = parseString(str);
        expect(str, ")");
        drv.outputs[id] = out;
    }

    /* Parse the list of input derivations. */
    expect(str, ",[");
    while (!endOfList(str)) {
        expect(str, "(");
        Path drvPath = parsePath(str);
        expect(str, ",[");
        drv.inputDrvs[drvPath] = parseStrings(str, false);
        expect(str, ")");
    }

    expect(str, ",["); drv.inputSrcs = parseStrings(str, true);
    expect(str, ","); drv.platform = parseString(str);
    expect(str, ","); drv.builder = parseString(str);

    /* Parse the builder arguments. */
    expect(str, ",[");
    while (!endOfList(str))
        drv.args.push_back(parseString(str));

    /* Parse the environment variables. */
    expect(str, ",[");
    while (!endOfList(str)) {
        expect(str, "("); string name = parseString(str);
        expect(str, ","); string value = parseString(str);
        expect(str, ")");
        drv.env[name] = value;
    }

    expect(str, ")");
    return drv;
}

Derivation readDerivation(const Path & drvPath)
{
    try {
        return parseDerivation(readFile(drvPath));
    } catch (FormatError & e) {
        throw Error(format("error parsing derivation `%1%': %2%") % drvPath % e.msg());
    }
}

static void printString(string & res, const string & s)
{
    res += '"';
    for (const char * i = s.c_str(); *i; i++)
        if (*i == '\"' || *i == '\\') { res += "\\"; res += *i; }
        else if (*i == '\n') res += "\\n";
        else if (*i == '\r') res += "\\r";
        else if (*i == '\t') res += "\\t";
        else res += *i;
    res += '"';
}

template<class ForwardIterator>
static void printStrings(string & res, ForwardIterator i, ForwardIterator j)
{
    res += '[';
    bool first = true;
    for ( ; i != j; ++i) {
        if (first) first = false; else res += ',';
        printString(res, *i);
    }
    res += ']';
}

string unparseDerivation(const Derivation & drv)
{
    string s;
    s.reserve(65536);
    s += "Derive([";

    bool first = true;
    foreach (DerivationOutputs::const_iterator, i, drv.outputs) {
        if (first) first = false; else s += ',';
        s += '('; printString(s, i->first);
        s += ','; printString(s, i->second.path);
        s += ','; printString(s, i->second.hashAlgo);
        s += ','; printString(s, i->second.hash);
        s += ')';
    }

    s += "],[";
    first = true;
    foreach (DerivationInputs::const_iterator, i, drv.inputDrvs) {
        if (first) first = false; else s += ',';
        s += '('; printString(s, i->first);
        s += ','; printStrings(s, i->second.begin(), i->second.end());
        s += ')';
    }

    s += "],";
    printStrings(s, drv.inputSrcs.begin(), drv.inputSrcs.end());

    s += ','; printString(s, drv.platform);
    s += ','; printString(s, drv.builder);
    s += ','; printStrings(s, drv.args.begin(), drv.args.end());

    s += ",[";
    first = true;
    foreach (StringPairs::const_iterator, i, drv.env) {
        if (first) first = false; else s += ',';
        s += '('; printString(s, i->first);
        s += ','; printString(s, i->second);
        s += ')';
    }

    s += "])";

    return s;
}

bool isDerivation(const string & fileName)
{
    return hasSuffix(fileName, drvExtension);
}

bool isFixedOutputDrv(const Derivation & drv)
{
    return drv.outputs.size() == 1 &&
        drv.outputs.begin()->first == "out" &&
        drv.outputs.begin()->second.hash != "";
}

DrvHashes drvHashes;

/* Returns the hash of a derivation modulo fixed-output
   subderivations.  A fixed-output derivation is a derivation with one
   output (`out') for which an expected hash and hash algorithm are
   specified (using the `outputHash' and `outputHashAlgo'
   attributes).  We don't want changes to such derivations to
   propagate upwards through the dependency graph, changing output
   paths everywhere.

   For instance, if we change the url in a call to the `fetchurl'
   function, we do not want to rebuild everything depending on it
   (after all, (the hash of) the file being downloaded is unchanged).
   So the *output paths* should not change.  On the other hand, the
   *derivation paths* should change to reflect the new dependency
   graph.

   That's what this function does: it returns a hash which is just the
   hash of the derivation ATerm, except that any input derivation
   paths have been replaced by the result of a recursive call to this
   function, and that for fixed-output derivations we return a hash of
   its output path. */
Hash hashDerivationModulo(StoreAPI & store, Derivation drv)
{
    /* Return a fixed hash for fixed-output derivations. */
    if (isFixedOutputDrv(drv)) {
        DerivationOutputs::const_iterator i = drv.outputs.begin();
        return hashString(htSHA256, "fixed:out:"
            + i->second.hashAlgo + ":"
            + i->second.hash + ":"
            + i->second.path);
    }

    /* For other derivations, replace the inputs paths with recursive
       calls to this function.*/
    DerivationInputs inputs2;
    foreach (DerivationInputs::const_iterator, i, drv.inputDrvs) {
        Hash h = drvHashes[i->first];
        if (h.type == htUnknown) {
            assert(store.isValidPath(i->first));
            Derivation drv2 = readDerivation(i->first);
            h = hashDerivationModulo(store, drv2);
            drvHashes[i->first] = h;
        }
        inputs2[printHash(h)] = i->second;
    }
    drv.inputDrvs = inputs2;

    return hashString(htSHA256, unparseDerivation(drv));
}

DrvPathWithOutputs parseDrvPathWithOutputs(const string & s)
{
    size_t n = s.find("!");
    return n == s.npos
        ? DrvPathWithOutputs(s, std::set<string>())
        : DrvPathWithOutputs(string(s, 0, n), tokenizeString<std::set<string> >(string(s, n + 1), ","));
}

Path makeDrvPathWithOutputs(const Path & drvPath, const std::set<string> & outputs)
{
    return outputs.empty()
        ? drvPath
        : drvPath + "!" + concatStringsSep(",", outputs);
}

bool wantOutput(const string & output, const std::set<string> & wanted)
{
    return wanted.empty() || wanted.find(output) != wanted.end();
}

PathSet outputPaths(const Derivation & drv)
{
    PathSet paths;
    for (auto & i : drv.outputs)
        paths.insert(i.second.path);
    return paths;
}

}


code:
#pragma once

#include "types.hh"
#include "hash.hh"

#include <map>

namespace nix {

/* Extension of derivations in the Nix store. */
const string drvExtension = ".drv";

/* Abstract syntax of derivations. */

struct DerivationOutput
{
    Path path;
    string hashAlgo; /* hash used for expected hash computation */
    string hash; /* expected hash, may be null */
    DerivationOutput()
    {
    }
    DerivationOutput(Path path, string hashAlgo, string hash)
    {
        this->path = path;
        this->hashAlgo = hashAlgo;
        this->hash = hash;
    }
    void parseHashInfo(bool & recursive, HashType & hashType, Hash & hash) const;
};

typedef std::map<string, DerivationOutput> DerivationOutputs;

/* For inputs that are sub-derivations, we specify exactly which
   output IDs we are interested in. */
typedef std::map<Path, StringSet> DerivationInputs;

typedef std::map<string, string> StringPairs;

struct Derivation
{
    DerivationOutputs outputs; /* keyed on symbolic IDs */
    DerivationInputs inputDrvs; /* inputs that are sub-derivations */
    PathSet inputSrcs; /* inputs that are sources */
    string platform;
    Path builder;
    Strings args;
    StringPairs env;
};

class StoreAPI;

/* Write a derivation to the Nix store, and return its path. */
Path writeDerivation(StoreAPI & store,
    const Derivation & drv, const string & name, bool repair = false);

/* Read a derivation from a file. */
Derivation readDerivation(const Path & drvPath);

/* Print a derivation. */
string unparseDerivation(const Derivation & drv);

/* Check whether a file name ends with the extensions for
   derivations. */
bool isDerivation(const string & fileName);

/* Return true iff this is a fixed-output derivation. */
bool isFixedOutputDrv(const Derivation & drv);

Hash hashDerivationModulo(StoreAPI & store, Derivation drv);

/* Memoisation of hashDerivationModulo(). */
typedef std::map<Path, Hash> DrvHashes;

extern DrvHashes drvHashes;

/* Split a string specifying a derivation and a set of outputs
   (/nix/store/hash-foo!out1,out2,...) into the derivation path and
   the outputs. */
typedef std::pair<string, std::set<string> > DrvPathWithOutputs;
DrvPathWithOutputs parseDrvPathWithOutputs(const string & s);

Path makeDrvPathWithOutputs(const Path & drvPath, const std::set<string> & outputs);

bool wantOutput(const string & output, const std::set<string> & wanted);

PathSet outputPaths(const Derivation & drv);

}


code:
#include "globals.hh"
#include "misc.hh"
#include "local-store.hh"

#include <functional>
#include <queue>
#include <algorithm>

#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <climits>

namespace nix {

static string gcLockName = "gc.lock";
static string tempRootsDir = "temproots";
static string gcRootsDir = "gcroots";

/* Acquire the global GC lock.  This is used to prevent new build
   processes from starting after the temporary root files have been
   read.  To be precise: when they try to create a new temporary root
   file, they will block until the garbage collector has finished /
   yielded the GC lock. */
int LocalStore::openGCLock(LockType lockType)
{
    Path fnGCLock = (format("%1%/%2%")
        % settings.nixStateDir % gcLockName).str();

    debug(format("acquiring global GC lock `%1%'") % fnGCLock);

    AutoCloseFD fdGCLock = open(fnGCLock.c_str(), O_RDWR | O_CREAT, 0600);
    if (fdGCLock == -1)
        throw SysError(format("opening global GC lock `%1%'") % fnGCLock);
    closeOnExec(fdGCLock);

    if (!lockFile(fdGCLock, lockType, false)) {
        printMsg(lvlError, format("waiting for the big garbage collector lock..."));
        lockFile(fdGCLock, lockType, true);
    }

    /* !!! Restrict read permission on the GC root.  Otherwise any
       process that can open the file for reading can DoS the
       collector. */

    return fdGCLock.borrow();
}

static void makeSymlink(const Path & link, const Path & target)
{
    /* Create directories up to `gcRoot'. */
    createDirs(dirOf(link));

    /* Create the new symlink. */
    Path tempLink = (format("%1%.tmp-%2%-%3%")
        % link % getpid() % rand()).str();
    createSymlink(target, tempLink);

    /* Atomically replace the old one. */
    if (rename(tempLink.c_str(), link.c_str()) == -1)
        throw SysError(format("cannot rename `%1%' to `%2%'")
            % tempLink % link);
}

void LocalStore::syncWithGC()
{
    AutoCloseFD fdGCLock = openGCLock(ltRead);
}

void LocalStore::addIndirectRoot(const Path & path)
{
    string hash = printHash32(hashString(htSHA1, path));
    Path realRoot = canonPath((format("%1%/%2%/auto/%3%")
        % settings.nixStateDir % gcRootsDir % hash).str());
    makeSymlink(realRoot, path);
}

Path addPermRoot(StoreAPI & store, const Path & _storePath,
    const Path & _gcRoot, bool indirect, bool allowOutsideRootsDir)
{
    Path storePath(canonPath(_storePath));
    Path gcRoot(canonPath(_gcRoot));
    assertStorePath(storePath);

    if (isInStore(gcRoot))
        throw Error(format(
                "creating a garbage collector root (%1%) in the store is forbidden "
                "(are you running nix-build inside the store?)") % gcRoot);

    if (indirect) {
        /* Don't clobber the link if it already exists and doesn't
           point to the store. */
        if (pathExists(gcRoot) && (!isLink(gcRoot) || !isInStore(readLink(gcRoot))))
            throw Error(format("cannot create symlink `%1%'; already exists") % gcRoot);
        makeSymlink(gcRoot, storePath);
        store.addIndirectRoot(gcRoot);
    }

    else {
        if (!allowOutsideRootsDir) {
            Path rootsDir = canonPath((format("%1%/%2%") % settings.nixStateDir % gcRootsDir).str());

            if (string(gcRoot, 0, rootsDir.size() + 1) != rootsDir + "/")
                throw Error(format(
                    "path `%1%' is not a valid garbage collector root; "
                    "it's not in the directory `%2%'")
                    % gcRoot % rootsDir);
        }

        if (baseNameOf(gcRoot) == baseNameOf(storePath))
            writeFile(gcRoot, "");
        else
            makeSymlink(gcRoot, storePath);
    }

    /* Check that the root can be found by the garbage collector.
       !!! This can be very slow on machines that have many roots.
       Instead of reading all the roots, it would be more efficient to
       check if the root is in a directory in or linked from the
       gcroots directory. */
    if (settings.checkRootReachability) {
        Roots roots = store.findRoots();
        if (roots.find(gcRoot) == roots.end())
            printMsg(lvlError,
                format(
                    "warning: `%1%' is not in a directory where the garbage collector looks for roots; "
                    "therefore, `%2%' might be removed by the garbage collector")
                % gcRoot % storePath);
    }

    /* Grab the global GC root, causing us to block while a GC is in
       progress.  This prevents the set of permanent roots from
       increasing while a GC is in progress. */
    store.syncWithGC();

    return gcRoot;
}

void LocalStore::addTempRoot(const Path & path)
{
    /* Create the temporary roots file for this process. */
    if (fdTempRoots == -1) {

        while (1) {
            Path dir = (format("%1%/%2%") % settings.nixStateDir % tempRootsDir).str();
            createDirs(dir);

            fnTempRoots = (format("%1%/%2%")
                % dir % getpid()).str();

            AutoCloseFD fdGCLock = openGCLock(ltRead);

            if (pathExists(fnTempRoots))
                /* It *must* be stale, since there can be no two
                   processes with the same pid. */
                unlink(fnTempRoots.c_str());

            fdTempRoots = openLockFile(fnTempRoots, true);

            fdGCLock.close();

            debug(format("acquiring read lock on `%1%'") % fnTempRoots);
            lockFile(fdTempRoots, ltRead, true);

            /* Check whether the garbage collector didn't get in our
               way. */
            struct stat st;
            if (fstat(fdTempRoots, &st) == -1)
                throw SysError(format("statting `%1%'") % fnTempRoots);
            if (st.st_size == 0) break;

            /* The garbage collector deleted this file before we could
               get a lock.  (It won't delete the file after we get a
               lock.)  Try again. */
        }

    }

    /* Upgrade the lock to a write lock.  This will cause us to block
       if the garbage collector is holding our lock. */
    debug(format("acquiring write lock on `%1%'") % fnTempRoots);
    lockFile(fdTempRoots, ltWrite, true);

    string s = path + '\0';
    writeFull(fdTempRoots, s);

    /* Downgrade to a read lock. */
    debug(format("downgrading to read lock on `%1%'") % fnTempRoots);
    lockFile(fdTempRoots, ltRead, true);
}

typedef std::shared_ptr<AutoCloseFD> FDPtr;
typedef list<FDPtr> FDs;

static void readTempRoots(PathSet & tempRoots, FDs & fds)
{
    /* Read the `temproots' directory for per-process temporary root
       files. */
    DirEntries tempRootFiles = readDirectory(
        (format("%1%/%2%") % settings.nixStateDir % tempRootsDir).str());

    for (auto & i : tempRootFiles) {
        Path path = (format("%1%/%2%/%3%") % settings.nixStateDir % tempRootsDir % i.name).str();

        debug(format("reading temporary root file `%1%'") % path);
        FDPtr fd(new AutoCloseFD(open(path.c_str(), O_RDWR, 0666)));
        if (*fd == -1) {
            /* It's okay if the file has disappeared. */
            if (errno == ENOENT) continue;
            throw SysError(format("opening temporary roots file `%1%'") % path);
        }

        /* This should work, but doesn't, for some reason. */
        //FDPtr fd(new AutoCloseFD(openLockFile(path, false)));
        //if (*fd == -1) continue;

        /* Try to acquire a write lock without blocking.  This can
           only succeed if the owning process has died.  In that case
           we don't care about its temporary roots. */
        if (lockFile(*fd, ltWrite, false)) {
            printMsg(lvlError, format("removing stale temporary roots file `%1%'") % path);
            unlink(path.c_str());
            writeFull(*fd, "d");
            continue;
        }

        /* Acquire a read lock.  This will prevent the owning process
           from upgrading to a write lock, therefore it will block in
           addTempRoot(). */
        debug(format("waiting for read lock on `%1%'") % path);
        lockFile(*fd, ltRead, true);

        /* Read the entire file. */
        string contents = readFile(*fd);

        /* Extract the roots. */
        string::size_type pos = 0, end;

        while ((end = contents.find((char) 0, pos)) != string::npos) {
            Path root(contents, pos, end - pos);
            debug(format("got temporary root `%1%'") % root);
            assertStorePath(root);
            tempRoots.insert(root);
            pos = end + 1;
        }

        fds.push_back(fd); /* keep open */
    }
}

static void foundRoot(StoreAPI & store,
    const Path & path, const Path & target, Roots & roots)
{
    Path storePath = toStorePath(target);
    if (store.isValidPath(storePath))
        roots[path] = storePath;
    else
        printMsg(lvlInfo, format("skipping invalid root from `%1%' to `%2%'") % path % storePath);
}

static void findRoots(StoreAPI & store, const Path & path, unsigned char type, Roots & roots)
{
    try {

        if (type == DT_UNKNOWN)
            type = getFileType(path);

        if (type == DT_DIR) {
            for (auto & i : readDirectory(path))
                findRoots(store, path + "/" + i.name, i.type, roots);
        }

        else if (type == DT_LNK) {
            Path target = readLink(path);
            if (isInStore(target))
                foundRoot(store, path, target, roots);

            /* Handle indirect roots. */
            else {
                target = absPath(target, dirOf(path));
                if (!pathExists(target)) {
                    if (isInDir(path, settings.nixStateDir + "/" + gcRootsDir + "/auto")) {
                        printMsg(lvlInfo, format("removing stale link from `%1%' to `%2%'") % path % target);
                        unlink(path.c_str());
                    }
                } else {
                    struct stat st2 = lstat(target);
                    if (!S_ISLNK(st2.st_mode)) return;
                    Path target2 = readLink(target);
                    if (isInStore(target2)) foundRoot(store, target, target2, roots);
                }
            }
        }

        else if (type == DT_REG) {
            Path storePath = settings.nixStore + "/" + baseNameOf(path);
            if (store.isValidPath(storePath))
                roots[path] = storePath;
        }

    }

    catch (SysError & e) {
        /* We only ignore permanent failures. */
        if (e.errNo == EACCES || e.errNo == ENOENT || e.errNo == ENOTDIR)
            printMsg(lvlInfo, format("cannot read potential root `%1%'") % path);
        else
            throw;
    }
}

Roots LocalStore::findRoots()
{
    Roots roots;

    /* Process direct roots in {gcroots,manifests,profiles}. */
    nix::findRoots(*this, settings.nixStateDir + "/" + gcRootsDir, DT_UNKNOWN, roots);
    if (pathExists(settings.nixStateDir + "/manifests"))
        nix::findRoots(*this, settings.nixStateDir + "/manifests", DT_UNKNOWN, roots);
    nix::findRoots(*this, settings.nixStateDir + "/profiles", DT_UNKNOWN, roots);

    return roots;
}

static void addAdditionalRoots(StoreAPI & store, PathSet & roots)
{
    debug(format("executing `%1% gc --list-busy' to find additional roots")
	  % settings.guixProgram);

    const Strings args = { "gc", "--list-busy" };
    string result = runProgram(settings.guixProgram, false, args);

    StringSet paths = tokenizeString<StringSet>(result, "\n");

    foreach (StringSet::iterator, i, paths) {
        if (isInStore(*i)) {
            Path path = toStorePath(*i);
            if (roots.find(path) == roots.end() && store.isValidPath(path)) {
                debug(format("got additional root `%1%'") % path);
                roots.insert(path);
            }
        }
    }
}

struct GCLimitReached { };

struct LocalStore::GCState
{
    GCOptions options;
    GCResults & results;
    PathSet roots;
    PathSet tempRoots;
    PathSet dead;
    PathSet alive;
    bool gcKeepOutputs;
    bool gcKeepDerivations;
    unsigned long long bytesInvalidated;
    bool moveToTrash = true;
    Path trashDir;
    bool shouldDelete;
    GCState(GCResults & results_) : results(results_), bytesInvalidated(0) { }
};

bool LocalStore::isActiveTempFile(const GCState & state,
    const Path & path, const string & suffix)
{
    return hasSuffix(path, suffix)
        && state.tempRoots.find(string(path, 0, path.size() - suffix.size())) != state.tempRoots.end();
}

void LocalStore::deleteGarbage(GCState & state, const Path & path)
{
    unsigned long long bytesFreed;

    /* When deduplication is on, store items always have at least two links:
       the one at PATH, and one in /gnu/store/.links.  In that case, increase
       bytesFreed when PATH has two or fewer links.  */
    size_t linkThreshold =
	(settings.autoOptimiseStore && isStorePath(path)) ? 2 : 1;

    deletePath(path, bytesFreed, linkThreshold);
    state.results.bytesFreed += bytesFreed;
}

void LocalStore::deletePathRecursive(GCState & state, const Path & path)
{
    checkInterrupt();

    unsigned long long size = 0;

    if (isValidPath(path)) {
        PathSet referrers;
        queryReferrers(path, referrers);
        foreach (PathSet::iterator, i, referrers)
            if (*i != path) deletePathRecursive(state, *i);
        size = queryPathInfo(path).narSize;
        invalidatePathChecked(path);
    }

    struct stat st;
    if (lstat(path.c_str(), &st)) {
        if (errno == ENOENT) return;
        throw SysError(format("getting status of %1%") % path);
    }

    if (state.options.maxFreed != ULLONG_MAX) {
	auto freed = state.results.bytesFreed + state.bytesInvalidated;
	double fraction = ((double) freed) / (double) state.options.maxFreed;
	unsigned int percentage = (fraction > 1. ? 1. : fraction) * 100.;
	printMsg(lvlInfo, format("[%1%%%] deleting '%2%'") % percentage % path);
    } else {
	auto freed = state.results.bytesFreed + state.bytesInvalidated;
	freed /=  1024ULL * 1024ULL;
	printMsg(lvlInfo, format("[%1% MiB] deleting '%2%'") % freed % path);
    }

    state.results.paths.insert(path);

    /* If the path is not a regular file or symlink, move it to the
       trash directory.  The move is to ensure that later (when we're
       not holding the global GC lock) we can delete the path without
       being afraid that the path has become alive again.  Otherwise
       delete it right away. */
    if (state.moveToTrash && S_ISDIR(st.st_mode)) {
        // Estimate the amount freed using the narSize field.  FIXME:
        // if the path was not valid, need to determine the actual
        // size.
        try {
            if (chmod(path.c_str(), st.st_mode | S_IWUSR) == -1)
                throw SysError(format("making `%1%' writable") % path);
            Path tmp = state.trashDir + "/" + baseNameOf(path);
            if (rename(path.c_str(), tmp.c_str()))
                throw SysError(format("unable to rename `%1%' to `%2%'") % path % tmp);
            state.bytesInvalidated += size;
        } catch (SysError & e) {
            /* In a Docker container, rename(2) returns EXDEV when the source
               and destination are not both on the "top layer".  See:
               https://bugs.gnu.org/41607 */
            if (e.errNo == ENOSPC || e.errNo == EXDEV) {
                printMsg(lvlInfo, format("note: can't create move `%1%': %2%") % path % e.msg());
                deleteGarbage(state, path);
            }
        }
    } else
        deleteGarbage(state, path);

    if (state.results.bytesFreed + state.bytesInvalidated > state.options.maxFreed) {
        printMsg(lvlInfo, format("deleted or invalidated more than %1% bytes; stopping") % state.options.maxFreed);
        throw GCLimitReached();
    }
}

bool LocalStore::canReachRoot(GCState & state, PathSet & visited, const Path & path)
{
    if (visited.find(path) != visited.end()) return false;

    if (state.alive.find(path) != state.alive.end()) {
        return true;
    }

    if (state.dead.find(path) != state.dead.end()) {
        return false;
    }

    if (state.roots.find(path) != state.roots.end()) {
        printMsg(lvlDebug, format("cannot delete `%1%' because it's a root") % path);
        state.alive.insert(path);
        return true;
    }

    visited.insert(path);

    if (!isValidPath(path)) return false;

    PathSet incoming;

    /* Don't delete this path if any of its referrers are alive. */
    queryReferrers(path, incoming);

    /* If gc-keep-derivations is set and this is a derivation, then
       don't delete the derivation if any of the outputs are alive. */
    if (state.gcKeepDerivations && isDerivation(path)) {
        PathSet outputs = queryDerivationOutputs(path);
        foreach (PathSet::iterator, i, outputs)
            if (isValidPath(*i) && queryDeriver(*i) == path)
                incoming.insert(*i);
    }

    /* If gc-keep-outputs is set, then don't delete this path if there
       are derivers of this path that are not garbage. */
    if (state.gcKeepOutputs) {
        PathSet derivers = queryValidDerivers(path);
        foreach (PathSet::iterator, i, derivers)
            incoming.insert(*i);
    }

    foreach (PathSet::iterator, i, incoming)
        if (*i != path)
            if (canReachRoot(state, visited, *i)) {
                state.alive.insert(path);
                return true;
            }

    return false;
}

void LocalStore::tryToDelete(GCState & state, const Path & path)
{
    checkInterrupt();

    if (path == linksDir || path == state.trashDir) return;

    startNest(nest, lvlDebug, format("considering whether to delete `%1%'") % path);

    if (!isValidPath(path)) {
        /* A lock file belonging to a path that we're building right
           now isn't garbage. */
        if (isActiveTempFile(state, path, ".lock")) return;

        /* Don't delete .chroot directories for derivations that are
           currently being built. */
        if (isActiveTempFile(state, path, ".chroot")) return;
    }

    PathSet visited;

    if (canReachRoot(state, visited, path)) {
        printMsg(lvlDebug, format("cannot delete `%1%' because it's still reachable") % path);
    } else {
        /* No path we visited was a root, so everything is garbage.
           But we only delete ‘path’ and its referrers here so that
           ‘nix-store --delete’ doesn't have the unexpected effect of
           recursing into derivations and outputs. */
        state.dead.insert(visited.begin(), visited.end());
        if (state.shouldDelete)
            deletePathRecursive(state, path);
    }
}

/* Unlink all files in /nix/store/.links that have a link count of 1,
   which indicates that there are no other links and so they can be
   safely deleted.  FIXME: race condition with optimisePath(): we
   might see a link count of 1 just before optimisePath() increases
   the link count. */
void LocalStore::removeUnusedLinks(const GCState & state)
{
    AutoCloseDir dir = opendir(linksDir.c_str());
    if (!dir) throw SysError(format("opening directory `%1%'") % linksDir);

    long long actualSize = 0, unsharedSize = 0;

    struct dirent * dirent;
    while (errno = 0, dirent = readdir(dir)) {
        checkInterrupt();
        string name = dirent->d_name;
        if (name == "." || name == "..") continue;
        Path path = linksDir + "/" + name;

#ifdef HAVE_STATX
# define st_size stx_size
# define st_nlink stx_nlink
	static int statx_flags = AT_SYMLINK_NOFOLLOW | AT_STATX_DONT_SYNC;
	struct statx st;

	if (statx(AT_FDCWD, path.c_str(), statx_flags,
		  STATX_SIZE | STATX_NLINK, &st) == -1) {
	    if (errno == EINVAL) {
		/* Old 3.10 kernels (CentOS 7) don't support
		   AT_STATX_DONT_SYNC, so try again without it.  */
		statx_flags &= ~AT_STATX_DONT_SYNC;
		if (statx(AT_FDCWD, path.c_str(), statx_flags,
			  STATX_SIZE | STATX_NLINK, &st) == -1)
		    throw SysError(format("statting `%1%'") % path);
	    } else {
		throw SysError(format("statting `%1%'") % path);
	    }
	}
#else
        struct stat st;
        if (lstat(path.c_str(), &st) == -1)
            throw SysError(format("statting `%1%'") % path);
#endif

        if (st.st_nlink != 1) {
            actualSize += st.st_size;
            unsharedSize += (st.st_nlink - 1) * st.st_size;
            continue;
        }

        printMsg(lvlTalkative, format("deleting unused link `%1%'") % path);

        if (unlink(path.c_str()) == -1)
            throw SysError(format("deleting `%1%'") % path);

        state.results.bytesFreed += st.st_size;
#undef st_size
#undef st_nlink
    }

    struct stat st;
    if (stat(linksDir.c_str(), &st) == -1)
        throw SysError(format("statting `%1%'") % linksDir);
    long long overhead = st.st_size;

    printMsg(lvlInfo, format("note: currently hard linking saves %.2f MiB")
        % ((unsharedSize - actualSize - overhead) / (1024.0 * 1024.0)));
}

void LocalStore::collectGarbage(const GCOptions & options, GCResults & results)
{
    GCState state(results);
    state.options = options;
    state.trashDir = settings.nixStore + "/trash";
    state.gcKeepOutputs = settings.gcKeepOutputs;
    state.gcKeepDerivations = settings.gcKeepDerivations;

    /* Using `--ignore-liveness' with `--delete' can have unintended
       consequences if `gc-keep-outputs' or `gc-keep-derivations' are
       true (the garbage collector will recurse into deleting the
       outputs or derivers, respectively).  So disable them. */
    if (options.action == GCOptions::gcDeleteSpecific && options.ignoreLiveness) {
        state.gcKeepOutputs = false;
        state.gcKeepDerivations = false;
    }

    state.shouldDelete = options.action == GCOptions::gcDeleteDead || options.action == GCOptions::gcDeleteSpecific;

    /* Acquire the global GC root.  This prevents
       a) New roots from being added.
       b) Processes from creating new temporary root files. */
    AutoCloseFD fdGCLock = openGCLock(ltWrite);

    /* Find the roots.  Since we've grabbed the GC lock, the set of
       permanent roots cannot increase now. */
    printMsg(lvlError, format("finding garbage collector roots..."));
    Roots rootMap = options.ignoreLiveness ? Roots() : findRoots();

    foreach (Roots::iterator, i, rootMap) state.roots.insert(i->second);

    /* Add additional roots returned by 'guix gc --list-busy'.  This is
       typically used to add running programs to the set of roots (to prevent
       them from being garbage collected). */
    if (!options.ignoreLiveness)
        addAdditionalRoots(*this, state.roots);

    /* Read the temporary roots.  This acquires read locks on all
       per-process temporary root files.  So after this point no paths
       can be added to the set of temporary roots. */
    FDs fds;
    readTempRoots(state.tempRoots, fds);
    state.roots.insert(state.tempRoots.begin(), state.tempRoots.end());

    /* After this point the set of roots or temporary roots cannot
       increase, since we hold locks on everything.  So everything
       that is not reachable from `roots' is garbage. */

    if (state.shouldDelete) {
        if (pathExists(state.trashDir)) deleteGarbage(state, state.trashDir);
        try {
            createDirs(state.trashDir);
        } catch (SysError & e) {
            if (e.errNo == ENOSPC) {
                printMsg(lvlInfo, format("note: can't create trash directory: %1%") % e.msg());
                state.moveToTrash = false;
            }
        }
    }

    /* Now either delete all garbage paths, or just the specified
       paths (for gcDeleteSpecific). */

    if (options.action == GCOptions::gcDeleteSpecific) {

        foreach (PathSet::iterator, i, options.pathsToDelete) {
            assertStorePath(*i);
            tryToDelete(state, *i);
            if (state.dead.find(*i) == state.dead.end())
                throw Error(format("cannot delete path `%1%' since it is still alive") % *i);
        }

    } else if (options.maxFreed > 0) {

        if (state.shouldDelete)
            printMsg(lvlError, format("deleting garbage..."));
        else
            printMsg(lvlError, format("determining live/dead paths..."));

        try {

            AutoCloseDir dir = opendir(settings.nixStore.c_str());
            if (!dir) throw SysError(format("opening directory `%1%'") % settings.nixStore);

            /* Read the store and immediately delete all paths that
               aren't valid.  When using --max-freed etc., deleting
               invalid paths is preferred over deleting unreachable
               paths, since unreachable paths could become reachable
               again.  We don't use readDirectory() here so that GCing
               can start faster. */
            Paths entries;
            struct dirent * dirent;
            while (errno = 0, dirent = readdir(dir)) {
                checkInterrupt();
                string name = dirent->d_name;
                if (name == "." || name == "..") continue;
                Path path = settings.nixStore + "/" + name;
                if (isValidPath(path))
                    entries.push_back(path);
                else
                    tryToDelete(state, path);
            }

            dir.close();

            /* Now delete the unreachable valid paths.  Randomise the
               order in which we delete entries to make the collector
               less biased towards deleting paths that come
               alphabetically first (e.g. /nix/store/000...).  This
               matters when using --max-freed etc. */
            vector<Path> entries_(entries.begin(), entries.end());
            random_shuffle(entries_.begin(), entries_.end());

            foreach (vector<Path>::iterator, i, entries_)
                tryToDelete(state, *i);

        } catch (GCLimitReached & e) {
        }
    }

    if (state.options.action == GCOptions::gcReturnLive) {
        state.results.paths = state.alive;
        return;
    }

    if (state.options.action == GCOptions::gcReturnDead) {
        state.results.paths = state.dead;
        return;
    }

    /* Allow other processes to add to the store from here on. */
    fdGCLock.close();
    fds.clear();

    /* Delete the trash directory. */
    printMsg(lvlInfo, format("deleting `%1%'") % state.trashDir);
    deleteGarbage(state, state.trashDir);

    /* Clean up the links directory. */
    if (options.action == GCOptions::gcDeleteDead || options.action == GCOptions::gcDeleteSpecific) {
        printMsg(lvlError, format("deleting unused links..."));
        removeUnusedLinks(state);
    }

    /* While we're at it, vacuum the database. */
    //if (options.action == GCOptions::gcDeleteDead) vacuumDB();
}

}


code:
#include "config.h"

#include "globals.hh"
#include "util.hh"
#include "archive.hh"

#include <map>
#include <algorithm>

namespace nix {

/* The default location of the daemon socket, relative to nixStateDir.
   The socket is in a directory to allow you to control access to the
   build daemon by setting the mode/ownership of the directory
   appropriately.  (This wouldn't work on the socket itself since it
   must be deleted and recreated on startup.) */
#define DEFAULT_SOCKET_PATH "/daemon-socket/socket"

Settings settings;

Settings::Settings()
{
    keepFailed = false;
    keepGoing = false;
    tryFallback = false;
    buildVerbosity = lvlError;
    maxBuildJobs = 1;
    buildCores = 1;
    readOnlyMode = false;
    thisSystem = SYSTEM;
    maxSilentTime = 0;
    buildTimeout = 0;
    useBuildHook = true;
    printBuildTrace = false;
    multiplexedBuildOutput = false;
    reservedSize = 8 * 1024 * 1024;
    fsyncMetadata = true;
    useSQLiteWAL = true;
    syncBeforeRegistering = false;
    useSubstitutes = true;
    useChroot = false;
    impersonateLinux26 = false;
    keepLog = true;
#if HAVE_BZLIB_H
    logCompression = COMPRESSION_BZIP2;
#else
    logCompression = COMPRESSION_GZIP;
#endif
    maxLogSize = 0;
    cacheFailure = false;
    pollInterval = 5;
    checkRootReachability = false;
    gcKeepOutputs = false;
    gcKeepDerivations = true;
    autoOptimiseStore = false;
    envKeepDerivations = false;
    lockCPU = getEnv("NIX_AFFINITY_HACK", "1") == "1";
    showTrace = false;
}

void Settings::processEnvironment()
{
    nixStore = canonPath(getEnv("NIX_STORE_DIR", getEnv("NIX_STORE", NIX_STORE_DIR)));
    nixLogDir = canonPath(getEnv("GUIX_LOG_DIRECTORY", NIX_LOG_DIR));
    nixStateDir = canonPath(getEnv("GUIX_STATE_DIRECTORY", NIX_STATE_DIR));
    nixDBPath = getEnv("GUIX_DATABASE_DIRECTORY", nixStateDir + "/db");
    nixConfDir = canonPath(getEnv("GUIX_CONFIGURATION_DIRECTORY", GUIX_CONFIGURATION_DIRECTORY));
    nixBinDir = canonPath(getEnv("NIX_BIN_DIR", NIX_BIN_DIR));
    nixDaemonSocketFile = canonPath(nixStateDir + DEFAULT_SOCKET_PATH);
    guixProgram = canonPath(getEnv("GUIX", nixBinDir + "/guix"));
}

void Settings::set(const string & name, const string & value)
{
    settings[name] = value;
    overrides[name] = value;
}

string Settings::get(const string & name, const string & def)
{
    auto i = settings.find(name);
    if (i == settings.end()) return def;
    return i->second;
}

Strings Settings::get(const string & name, const Strings & def)
{
    auto i = settings.find(name);
    if (i == settings.end()) return def;
    return tokenizeString<Strings>(i->second);
}

bool Settings::get(const string & name, bool def)
{
    bool res = def;
    _get(res, name);
    return res;
}

int Settings::get(const string & name, int def)
{
    int res = def;
    _get(res, name);
    return res;
}

void Settings::update()
{
    _get(tryFallback, "build-fallback");
    _get(maxBuildJobs, "build-max-jobs");
    _get(buildCores, "build-cores");
    _get(thisSystem, "system");
    _get(multiplexedBuildOutput, "multiplexed-build-output");
    _get(maxSilentTime, "build-max-silent-time");
    _get(buildTimeout, "build-timeout");
    _get(reservedSize, "gc-reserved-space");
    _get(fsyncMetadata, "fsync-metadata");
    _get(useSQLiteWAL, "use-sqlite-wal");
    _get(syncBeforeRegistering, "sync-before-registering");
    _get(useSubstitutes, "build-use-substitutes");
    _get(buildUsersGroup, "build-users-group");
    _get(useChroot, "build-use-chroot");
    _get(impersonateLinux26, "build-impersonate-linux-26");
    _get(keepLog, "build-keep-log");
    // _get(logCompression, "build-log-compression");
    _get(maxLogSize, "build-max-log-size");
    _get(cacheFailure, "build-cache-failure");
    _get(pollInterval, "build-poll-interval");
    _get(checkRootReachability, "gc-check-reachability");
    _get(gcKeepOutputs, "gc-keep-outputs");
    _get(gcKeepDerivations, "gc-keep-derivations");
    _get(autoOptimiseStore, "auto-optimise-store");
    _get(envKeepDerivations, "env-keep-derivations");
}

void Settings::_get(string & res, const string & name)
{
    SettingsMap::iterator i = settings.find(name);
    if (i == settings.end()) return;
    res = i->second;
}

void Settings::_get(bool & res, const string & name)
{
    SettingsMap::iterator i = settings.find(name);
    if (i == settings.end()) return;
    if (i->second == "true") res = true;
    else if (i->second == "false") res = false;
    else throw Error(format("configuration option `%1%' should be either `true' or `false', not `%2%'")
        % name % i->second);
}

void Settings::_get(StringSet & res, const string & name)
{
    SettingsMap::iterator i = settings.find(name);
    if (i == settings.end()) return;
    res.clear();
    Strings ss = tokenizeString<Strings>(i->second);
    res.insert(ss.begin(), ss.end());
}

void Settings::_get(Strings & res, const string & name)
{
    SettingsMap::iterator i = settings.find(name);
    if (i == settings.end()) return;
    res = tokenizeString<Strings>(i->second);
}

template<class N> void Settings::_get(N & res, const string & name)
{
    SettingsMap::iterator i = settings.find(name);
    if (i == settings.end()) return;
    if (!string2Int(i->second, res))
        throw Error(format("configuration setting `%1%' should have an integer value") % name);
}

string Settings::pack()
{
    string s;
    foreach (SettingsMap::iterator, i, settings) {
        if (i->first.find('\n') != string::npos ||
            i->first.find('=') != string::npos ||
            i->second.find('\n') != string::npos)
            throw Error("invalid option name/value");
        s += i->first; s += '='; s += i->second; s += '\n';
    }
    return s;
}

Settings::SettingsMap Settings::getOverrides()
{
    return overrides;
}

const string nixVersion = PACKAGE_VERSION;

}


code:
#pragma once

#include "config.h"
#include "types.hh"

#include <map>
#include <sys/types.h>

namespace nix {

enum CompressionType
{
    COMPRESSION_NONE = 0,
    COMPRESSION_GZIP = 1
#if HAVE_BZLIB_H
    , COMPRESSION_BZIP2 = 2
#endif
};

struct Settings {

    typedef std::map<string, string> SettingsMap;

    Settings();

    void processEnvironment();

    void set(const string & name, const string & value);

    string get(const string & name, const string & def);

    Strings get(const string & name, const Strings & def);

    bool get(const string & name, bool def);

    int get(const string & name, int def);

    void update();

    string pack();

    SettingsMap getOverrides();

    /* The directory where we store sources and derived files. */
    Path nixStore;

    /* The directory where we log various operations. */
    Path nixLogDir;

    /* The directory where state is stored. */
    Path nixStateDir;

    /* The directory where we keep the SQLite database. */
    Path nixDBPath;

    /* The directory where configuration files are stored. */
    Path nixConfDir;

    /* The directory where the main programs are stored. */
    Path nixBinDir;

    /* File name of the socket the daemon listens to.  */
    Path nixDaemonSocketFile;

    /* Absolute file name of the 'guix' program.  */
    Path guixProgram;

    /* Whether to keep temporary directories of failed builds. */
    bool keepFailed;

    /* Whether to keep building subgoals when a sibling (another
       subgoal of the same goal) fails. */
    bool keepGoing;

    /* User and groud id of the client issuing the build request.  Used to set
       the owner and group of the kept temporary directories of failed
       builds. */
    uid_t clientUid;
    gid_t clientGid;

    /* Whether, if we cannot realise the known closure corresponding
       to a derivation, we should try to normalise the derivation
       instead. */
    bool tryFallback;

    /* Verbosity level for build output. */
    Verbosity buildVerbosity;

    /* Maximum number of parallel build jobs.  0 means unlimited. */
    unsigned int maxBuildJobs;

    /* Number of CPU cores to utilize in parallel within a build,
       i.e. by passing this number to Make via '-j'. 0 means that the
       number of actual CPU cores on the local host ought to be
       auto-detected. */
    unsigned int buildCores;

    /* Read-only mode.  Don't copy stuff to the store, don't change
       the database. */
    bool readOnlyMode;

    /* The canonical system name, as returned by config.guess. */
    string thisSystem;

    /* The maximum time in seconds that a builer can go without
       producing any output on stdout/stderr before it is killed.  0
       means infinity. */
    time_t maxSilentTime;

    /* The maximum duration in seconds that a builder can run.  0
       means infinity.  */
    time_t buildTimeout;

    /* Whether to use build hooks (for distributed builds).  Sometimes
       users want to disable this from the command-line. */
    bool useBuildHook;

    /* Whether buildDerivations() should print out lines on stderr in
       a fixed format to allow its progress to be monitored.  Each
       line starts with a "@".  The following are defined:

       @ build-started <drvpath> <outpath> <system> <logfile> <pid>
       @ build-failed <drvpath> <outpath> <exitcode> <error text>
       @ build-succeeded <drvpath> <outpath>
       @ substituter-started <outpath> <substituter>
       @ substituter-failed <outpath> <exitcode> <error text>
       @ substituter-succeeded <outpath>

       Best combined with --no-build-output, otherwise stderr might
       conceivably contain lines in this format printed by the
       builders. */
    bool printBuildTrace;

    /* When true, 'buildDerivations' prefixes lines coming from builders so
       that clients know exactly which line comes from which builder, and
       which line comes from the daemon itself.  The prefix for data coming
       from builders is "log:PID:LEN:DATA" where PID uniquely identifies the
       builder (PID is given in "build-started" traces.)  */
    bool multiplexedBuildOutput;

    /* Amount of reserved space for the garbage collector
       (/nix/var/nix/db/reserved). */
    off_t reservedSize;

    /* Whether SQLite should use fsync. */
    bool fsyncMetadata;

    /* Whether SQLite should use WAL mode. */
    bool useSQLiteWAL;

    /* Whether to call sync() before registering a path as valid. */
    bool syncBeforeRegistering;

    /* Whether to use substitutes. */
    bool useSubstitutes;

    /* The Unix group that contains the build users. */
    string buildUsersGroup;

    /* Whether to build in chroot. */
    bool useChroot;

    /* Whether to impersonate a Linux 2.6 machine on newer kernels. */
    bool impersonateLinux26;

    /* Whether to store build logs. */
    bool keepLog;

    /* Whether to compress logs. */
    enum CompressionType logCompression;

    /* Maximum number of bytes a builder can write to stdout/stderr
       before being killed (0 means no limit). */
    unsigned long maxLogSize;

    /* Whether to cache build failures. */
    bool cacheFailure;

    /* How often (in seconds) to poll for locks. */
    unsigned int pollInterval;

    /* Whether to check if new GC roots can in fact be found by the
       garbage collector. */
    bool checkRootReachability;

    /* Whether the garbage collector should keep outputs of live
       derivations. */
    bool gcKeepOutputs;

    /* Whether the garbage collector should keep derivers of live
       paths. */
    bool gcKeepDerivations;

    /* Whether to automatically replace files with identical contents
       with hard links. */
    bool autoOptimiseStore;

    /* Whether to add derivations as a dependency of user environments
       (to prevent them from being GCed). */
    bool envKeepDerivations;

    /* Whether to lock the Nix client and worker to the same CPU. */
    bool lockCPU;

    /* Whether to show a stack trace if Nix evaluation fails. */
    bool showTrace;

private:
    SettingsMap settings, overrides;

    void _get(string & res, const string & name);
    void _get(bool & res, const string & name);
    void _get(StringSet & res, const string & name);
    void _get(Strings & res, const string & name);
    template<class N> void _get(N & res, const string & name);
};

// FIXME: don't use a global variable.
extern Settings settings;

extern const string nixVersion;

}