id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
10,842
log-store.cc
NixOS_nix/src/libstore/log-store.cc
#include "log-store.hh" namespace nix { std::optional<std::string> LogStore::getBuildLog(const StorePath & path) { auto maybePath = getBuildDerivationPath(path); if (!maybePath) return std::nullopt; return getBuildLogExact(maybePath.value()); } }
270
C++
.cc
9
26.444444
74
0.728682
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,843
personality.cc
NixOS_nix/src/libstore/linux/personality.cc
#include "personality.hh" #include "globals.hh" #include <sys/utsname.h> #include <sys/personality.h> #include <cstring> namespace nix::linux { void setPersonality(std::string_view system) { /* Change the personality to 32-bit if we're doing an i686-linux build on an x86_64-linux machine. */ struct utsname utsbuf; uname(&utsbuf); if ((system == "i686-linux" && (std::string_view(SYSTEM) == "x86_64-linux" || (!strcmp(utsbuf.sysname, "Linux") && !strcmp(utsbuf.machine, "x86_64")))) || system == "armv7l-linux" || system == "armv6l-linux" || system == "armv5tel-linux") { if (personality(PER_LINUX32) == -1) throw SysError("cannot set 32-bit personality"); } /* Impersonate a Linux 2.6 machine to get some determinism in builds that depend on the kernel version. */ if ((system == "i686-linux" || system == "x86_64-linux") && settings.impersonateLinux26) { int cur = personality(0xffffffff); if (cur != -1) personality(cur | 0x0020000 /* == UNAME26 */); } /* Disable address space randomization for improved determinism. */ int cur = personality(0xffffffff); if (cur != -1) personality(cur | ADDR_NO_RANDOMIZE); } }
1,377
C++
.cc
34
31.852941
98
0.582335
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,844
fetchurl.cc
NixOS_nix/src/libstore/builtins/fetchurl.cc
#include "builtins.hh" #include "filetransfer.hh" #include "store-api.hh" #include "archive.hh" #include "compression.hh" namespace nix { void builtinFetchurl( const BasicDerivation & drv, const std::map<std::string, Path> & outputs, const std::string & netrcData, const std::string & caFileData) { /* Make the host's netrc data available. Too bad curl requires this to be stored in a file. It would be nice if we could just pass a pointer to the data. */ if (netrcData != "") { settings.netrcFile = "netrc"; writeFile(settings.netrcFile, netrcData, 0600); } settings.caFile = "ca-certificates.crt"; writeFile(settings.caFile, caFileData, 0600); auto out = get(drv.outputs, "out"); if (!out) throw Error("'builtin:fetchurl' requires an 'out' output"); if (!(drv.type().isFixed() || drv.type().isImpure())) throw Error("'builtin:fetchurl' must be a fixed-output or impure derivation"); auto storePath = outputs.at("out"); auto mainUrl = drv.env.at("url"); bool unpack = getOr(drv.env, "unpack", "") == "1"; /* Note: have to use a fresh fileTransfer here because we're in a forked process. */ auto fileTransfer = makeFileTransfer(); auto fetch = [&](const std::string & url) { auto source = sinkToSource([&](Sink & sink) { FileTransferRequest request(url); request.decompress = false; auto decompressor = makeDecompressionSink( unpack && hasSuffix(mainUrl, ".xz") ? "xz" : "none", sink); fileTransfer->download(std::move(request), *decompressor); decompressor->finish(); }); if (unpack) restorePath(storePath, *source); else writeFile(storePath, *source); auto executable = drv.env.find("executable"); if (executable != drv.env.end() && executable->second == "1") { if (chmod(storePath.c_str(), 0755) == -1) throw SysError("making '%1%' executable", storePath); } }; /* Try the hashed mirrors first. */ auto dof = std::get_if<DerivationOutput::CAFixed>(&out->raw); if (dof && dof->ca.method.getFileIngestionMethod() == FileIngestionMethod::Flat) for (auto hashedMirror : settings.hashedMirrors.get()) try { if (!hasSuffix(hashedMirror, "/")) hashedMirror += '/'; fetch(hashedMirror + printHashAlgo(dof->ca.hash.algo) + "/" + dof->ca.hash.to_string(HashFormat::Base16, false)); return; } catch (Error & e) { debug(e.what()); } /* Otherwise try the specified URL. */ fetch(mainUrl); } }
2,740
C++
.cc
66
33.590909
129
0.605342
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,845
unpack-channel.cc
NixOS_nix/src/libstore/builtins/unpack-channel.cc
#include "builtins.hh" #include "tarfile.hh" namespace nix { namespace fs { using namespace std::filesystem; } void builtinUnpackChannel( const BasicDerivation & drv, const std::map<std::string, Path> & outputs) { auto getAttr = [&](const std::string & name) -> const std::string & { auto i = drv.env.find(name); if (i == drv.env.end()) throw Error("attribute '%s' missing", name); return i->second; }; fs::path out{outputs.at("out")}; auto & channelName = getAttr("channelName"); auto & src = getAttr("src"); if (fs::path{channelName}.filename().string() != channelName) { throw Error("channelName is not allowed to contain filesystem separators, got %1%", channelName); } try { fs::create_directories(out); } catch (fs::filesystem_error &) { throw SysError("creating directory '%1%'", out.string()); } unpackTarfile(src, out); size_t fileCount; std::string fileName; try { auto entries = fs::directory_iterator{out}; fileName = entries->path().string(); fileCount = std::distance(fs::begin(entries), fs::end(entries)); } catch (fs::filesystem_error &) { throw SysError("failed to read directory %1%", out.string()); } if (fileCount != 1) throw Error("channel tarball '%s' contains more than one file", src); auto target = out / channelName; try { fs::rename(fileName, target); } catch (fs::filesystem_error &) { throw SysError("failed to rename %1% to %2%", fileName, target.string()); } } }
1,601
C++
.cc
44
30.681818
105
0.624838
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,846
buildenv.cc
NixOS_nix/src/libstore/builtins/buildenv.cc
#include "buildenv.hh" #include "derivations.hh" #include "signals.hh" #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <algorithm> namespace nix { struct State { std::map<Path, int> priorities; unsigned long symlinks = 0; }; /* For each activated package, create symlinks */ static void createLinks(State & state, const Path & srcDir, const Path & dstDir, int priority) { std::filesystem::directory_iterator srcFiles; try { srcFiles = std::filesystem::directory_iterator{srcDir}; } catch (std::filesystem::filesystem_error & e) { if (e.code() == std::errc::not_a_directory) { warn("not including '%s' in the user environment because it's not a directory", srcDir); return; } throw; } for (const auto & ent : srcFiles) { checkInterrupt(); auto name = ent.path().filename(); if (name.string()[0] == '.') /* not matched by glob */ continue; auto srcFile = (std::filesystem::path{srcDir} / name).string(); auto dstFile = (std::filesystem::path{dstDir} / name).string(); struct stat srcSt; try { if (stat(srcFile.c_str(), &srcSt) == -1) throw SysError("getting status of '%1%'", srcFile); } catch (SysError & e) { if (e.errNo == ENOENT || e.errNo == ENOTDIR) { warn("skipping dangling symlink '%s'", dstFile); continue; } throw; } /* The files below are special-cased to that they don't show * up in user profiles, either because they are useless, or * because they would cause pointless collisions (e.g., each * Python package brings its own * `$out/lib/pythonX.Y/site-packages/easy-install.pth'.) */ if (hasSuffix(srcFile, "/propagated-build-inputs") || hasSuffix(srcFile, "/nix-support") || hasSuffix(srcFile, "/perllocal.pod") || hasSuffix(srcFile, "/info/dir") || hasSuffix(srcFile, "/log") || hasSuffix(srcFile, "/manifest.nix") || hasSuffix(srcFile, "/manifest.json")) continue; else if (S_ISDIR(srcSt.st_mode)) { auto dstStOpt = maybeLstat(dstFile.c_str()); if (dstStOpt) { auto & dstSt = *dstStOpt; if (S_ISDIR(dstSt.st_mode)) { createLinks(state, srcFile, dstFile, priority); continue; } else if (S_ISLNK(dstSt.st_mode)) { auto target = canonPath(dstFile, true); if (!S_ISDIR(lstat(target).st_mode)) throw Error("collision between '%1%' and non-directory '%2%'", srcFile, target); if (unlink(dstFile.c_str()) == -1) throw SysError("unlinking '%1%'", dstFile); if (mkdir(dstFile.c_str() #ifndef _WIN32 // TODO abstract mkdir perms for Windows , 0755 #endif ) == -1) throw SysError("creating directory '%1%'", dstFile); createLinks(state, target, dstFile, state.priorities[dstFile]); createLinks(state, srcFile, dstFile, priority); continue; } } } else { auto dstStOpt = maybeLstat(dstFile.c_str()); if (dstStOpt) { auto & dstSt = *dstStOpt; if (S_ISLNK(dstSt.st_mode)) { auto prevPriority = state.priorities[dstFile]; if (prevPriority == priority) throw BuildEnvFileConflictError( readLink(dstFile), srcFile, priority ); if (prevPriority < priority) continue; if (unlink(dstFile.c_str()) == -1) throw SysError("unlinking '%1%'", dstFile); } else if (S_ISDIR(dstSt.st_mode)) throw Error("collision between non-directory '%1%' and directory '%2%'", srcFile, dstFile); } } createSymlink(srcFile, dstFile); state.priorities[dstFile] = priority; state.symlinks++; } } void buildProfile(const Path & out, Packages && pkgs) { State state; std::set<Path> done, postponed; auto addPkg = [&](const Path & pkgDir, int priority) { if (!done.insert(pkgDir).second) return; createLinks(state, pkgDir, out, priority); try { for (const auto & p : tokenizeString<std::vector<std::string>>( readFile(pkgDir + "/nix-support/propagated-user-env-packages"), " \n")) if (!done.count(p)) postponed.insert(p); } catch (SysError & e) { if (e.errNo != ENOENT && e.errNo != ENOTDIR) throw; } }; /* Symlink to the packages that have been installed explicitly by the * user. Process in priority order to reduce unnecessary * symlink/unlink steps. */ std::sort(pkgs.begin(), pkgs.end(), [](const Package & a, const Package & b) { return a.priority < b.priority || (a.priority == b.priority && a.path < b.path); }); for (const auto & pkg : pkgs) if (pkg.active) addPkg(pkg.path, pkg.priority); /* Symlink to the packages that have been "propagated" by packages * installed by the user (i.e., package X declares that it wants Y * installed as well). We do these later because they have a lower * priority in case of collisions. */ auto priorityCounter = 1000; while (!postponed.empty()) { std::set<Path> pkgDirs; postponed.swap(pkgDirs); for (const auto & pkgDir : pkgDirs) addPkg(pkgDir, priorityCounter++); } debug("created %d symlinks in user environment", state.symlinks); } void builtinBuildenv( const BasicDerivation & drv, const std::map<std::string, Path> & outputs) { auto getAttr = [&](const std::string & name) { auto i = drv.env.find(name); if (i == drv.env.end()) throw Error("attribute '%s' missing", name); return i->second; }; auto out = outputs.at("out"); createDirs(out); /* Convert the stuff we get from the environment back into a * coherent data type. */ Packages pkgs; { auto derivations = tokenizeString<Strings>(getAttr("derivations")); auto itemIt = derivations.begin(); while (itemIt != derivations.end()) { /* !!! We're trusting the caller to structure derivations env var correctly */ const bool active = "false" != *itemIt++; const int priority = stoi(*itemIt++); const size_t outputs = stoul(*itemIt++); for (size_t n {0}; n < outputs; n++) { pkgs.emplace_back(std::move(*itemIt++), active, priority); } } } buildProfile(out, std::move(pkgs)); createSymlink(getAttr("manifest"), out + "/manifest.nix"); } }
7,313
C++
.cc
180
29.744444
111
0.545237
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
10,847
pathlocks.cc
NixOS_nix/src/libstore/unix/pathlocks.cc
#include "pathlocks.hh" #include "util.hh" #include "sync.hh" #include "signals.hh" #include <cerrno> #include <cstdlib> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/file.h> namespace nix { AutoCloseFD openLockFile(const Path & path, bool create) { AutoCloseFD fd; fd = open(path.c_str(), O_CLOEXEC | O_RDWR | (create ? O_CREAT : 0), 0600); if (!fd && (create || errno != ENOENT)) throw SysError("opening lock file '%1%'", path); return fd; } void deleteLockFile(const Path & path, Descriptor desc) { /* Get rid of the lock file. Have to be careful not to introduce races. Write a (meaningless) token to the file to indicate to other processes waiting on this lock that the lock is stale (deleted). */ unlink(path.c_str()); writeFull(desc, "d"); /* Note that the result of unlink() is ignored; removing the lock file is an optimisation, not a necessity. */ } bool lockFile(Descriptor desc, LockType lockType, bool wait) { int type; if (lockType == ltRead) type = LOCK_SH; else if (lockType == ltWrite) type = LOCK_EX; else if (lockType == ltNone) type = LOCK_UN; else unreachable(); if (wait) { while (flock(desc, type) != 0) { checkInterrupt(); if (errno != EINTR) throw SysError("acquiring/releasing lock"); else return false; } } else { while (flock(desc, type | LOCK_NB) != 0) { checkInterrupt(); if (errno == EWOULDBLOCK) return false; if (errno != EINTR) throw SysError("acquiring/releasing lock"); } } return true; } bool PathLocks::lockPaths(const PathSet & paths, const std::string & waitMsg, bool wait) { assert(fds.empty()); /* Note that `fds' is built incrementally so that the destructor will only release those locks that we have already acquired. */ /* Acquire the lock for each path in sorted order. This ensures that locks are always acquired in the same order, thus preventing deadlocks. */ for (auto & path : paths) { checkInterrupt(); Path lockPath = path + ".lock"; debug("locking path '%1%'", path); AutoCloseFD fd; while (1) { /* Open/create the lock file. */ fd = openLockFile(lockPath, true); /* Acquire an exclusive lock. */ if (!lockFile(fd.get(), ltWrite, false)) { if (wait) { if (waitMsg != "") printError(waitMsg); lockFile(fd.get(), ltWrite, true); } else { /* Failed to lock this path; release all other locks. */ unlock(); return false; } } debug("lock acquired on '%1%'", lockPath); /* Check that the lock file hasn't become stale (i.e., hasn't been unlinked). */ struct stat st; if (fstat(fd.get(), &st) == -1) throw SysError("statting lock file '%1%'", lockPath); if (st.st_size != 0) /* This lock file has been unlinked, so we're holding a lock on a deleted file. This means that other processes may create and acquire a lock on `lockPath', and proceed. So we must retry. */ debug("open lock file '%1%' has become stale", lockPath); else break; } /* Use borrow so that the descriptor isn't closed. */ fds.push_back(FDPair(fd.release(), lockPath)); } return true; } void PathLocks::unlock() { for (auto & i : fds) { if (deletePaths) deleteLockFile(i.second, i.first); if (close(i.first) == -1) printError( "error (ignored): cannot close lock file on '%1%'", i.second); debug("lock released on '%1%'", i.second); } fds.clear(); } FdLock::FdLock(Descriptor desc, LockType lockType, bool wait, std::string_view waitMsg) : desc(desc) { if (wait) { if (!lockFile(desc, lockType, false)) { printInfo("%s", waitMsg); acquired = lockFile(desc, lockType, true); } } else acquired = lockFile(desc, lockType, false); } }
4,467
C++
.cc
128
26.21875
87
0.561338
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
10,848
user-lock.cc
NixOS_nix/src/libstore/unix/user-lock.cc
#include <vector> #include <pwd.h> #include <grp.h> #include "user-lock.hh" #include "file-system.hh" #include "globals.hh" #include "pathlocks.hh" #include "users.hh" namespace nix { #if __linux__ static std::vector<gid_t> get_group_list(const char *username, gid_t group_id) { std::vector<gid_t> gids; gids.resize(32); // Initial guess auto getgroupl_failed {[&] { int ngroups = gids.size(); int err = getgrouplist(username, group_id, gids.data(), &ngroups); gids.resize(ngroups); return err == -1; }}; // The first error means that the vector was not big enough. // If it happens again, there is some different problem. if (getgroupl_failed() && getgroupl_failed()) { throw SysError("failed to get list of supplementary groups for '%s'", username); } return gids; } #endif struct SimpleUserLock : UserLock { AutoCloseFD fdUserLock; uid_t uid; gid_t gid; std::vector<gid_t> supplementaryGIDs; uid_t getUID() override { assert(uid); return uid; } uid_t getUIDCount() override { return 1; } gid_t getGID() override { assert(gid); return gid; } std::vector<gid_t> getSupplementaryGIDs() override { return supplementaryGIDs; } static std::unique_ptr<UserLock> acquire() { assert(settings.buildUsersGroup != ""); createDirs(settings.nixStateDir + "/userpool"); /* Get the members of the build-users-group. */ struct group * gr = getgrnam(settings.buildUsersGroup.get().c_str()); if (!gr) throw Error("the group '%s' specified in 'build-users-group' does not exist", settings.buildUsersGroup); /* Copy the result of getgrnam. */ Strings users; for (char * * p = gr->gr_mem; *p; ++p) { debug("found build user '%s'", *p); users.push_back(*p); } if (users.empty()) throw Error("the build users group '%s' has no members", settings.buildUsersGroup); /* Find a user account that isn't currently in use for another build. */ for (auto & i : users) { debug("trying user '%s'", i); struct passwd * pw = getpwnam(i.c_str()); if (!pw) throw Error("the user '%s' in the group '%s' does not exist", i, settings.buildUsersGroup); auto fnUserLock = fmt("%s/userpool/%s", settings.nixStateDir,pw->pw_uid); AutoCloseFD fd = open(fnUserLock.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0600); if (!fd) throw SysError("opening user lock '%s'", fnUserLock); if (lockFile(fd.get(), ltWrite, false)) { auto lock = std::make_unique<SimpleUserLock>(); lock->fdUserLock = std::move(fd); lock->uid = pw->pw_uid; lock->gid = gr->gr_gid; /* Sanity check... */ if (lock->uid == getuid() || lock->uid == geteuid()) throw Error("the Nix user should not be a member of '%s'", settings.buildUsersGroup); #if __linux__ /* Get the list of supplementary groups of this user. This is * usually either empty or contains a group such as "kvm". */ // Finally, trim back the GID list to its real size. for (auto gid : get_group_list(pw->pw_name, pw->pw_gid)) { if (gid != lock->gid) lock->supplementaryGIDs.push_back(gid); } #endif return lock; } } return nullptr; } }; struct AutoUserLock : UserLock { AutoCloseFD fdUserLock; uid_t firstUid = 0; gid_t firstGid = 0; uid_t nrIds = 1; uid_t getUID() override { assert(firstUid); return firstUid; } gid_t getUIDCount() override { return nrIds; } gid_t getGID() override { assert(firstGid); return firstGid; } std::vector<gid_t> getSupplementaryGIDs() override { return {}; } static std::unique_ptr<UserLock> acquire(uid_t nrIds, bool useUserNamespace) { #if !defined(__linux__) useUserNamespace = false; #endif experimentalFeatureSettings.require(Xp::AutoAllocateUids); assert(settings.startId > 0); assert(settings.uidCount % maxIdsPerBuild == 0); assert((uint64_t) settings.startId + (uint64_t) settings.uidCount <= std::numeric_limits<uid_t>::max()); assert(nrIds <= maxIdsPerBuild); createDirs(settings.nixStateDir + "/userpool2"); size_t nrSlots = settings.uidCount / maxIdsPerBuild; for (size_t i = 0; i < nrSlots; i++) { debug("trying user slot '%d'", i); createDirs(settings.nixStateDir + "/userpool2"); auto fnUserLock = fmt("%s/userpool2/slot-%d", settings.nixStateDir, i); AutoCloseFD fd = open(fnUserLock.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0600); if (!fd) throw SysError("opening user lock '%s'", fnUserLock); if (lockFile(fd.get(), ltWrite, false)) { auto firstUid = settings.startId + i * maxIdsPerBuild; auto pw = getpwuid(firstUid); if (pw) throw Error("auto-allocated UID %d clashes with existing user account '%s'", firstUid, pw->pw_name); auto lock = std::make_unique<AutoUserLock>(); lock->fdUserLock = std::move(fd); lock->firstUid = firstUid; if (useUserNamespace) lock->firstGid = firstUid; else { struct group * gr = getgrnam(settings.buildUsersGroup.get().c_str()); if (!gr) throw Error("the group '%s' specified in 'build-users-group' does not exist", settings.buildUsersGroup); lock->firstGid = gr->gr_gid; } lock->nrIds = nrIds; return lock; } } return nullptr; } }; std::unique_ptr<UserLock> acquireUserLock(uid_t nrIds, bool useUserNamespace) { if (settings.autoAllocateUids) return AutoUserLock::acquire(nrIds, useUserNamespace); else return SimpleUserLock::acquire(); } bool useBuildUsers() { #if __linux__ static bool b = (settings.buildUsersGroup != "" || settings.autoAllocateUids) && isRootUser(); return b; #elif __APPLE__ static bool b = settings.buildUsersGroup != "" && isRootUser(); return b; #else return false; #endif } }
6,631
C++
.cc
160
31.925
128
0.579857
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,849
local-derivation-goal.cc
NixOS_nix/src/libstore/unix/build/local-derivation-goal.cc
#include "local-derivation-goal.hh" #include "indirect-root-store.hh" #include "hook-instance.hh" #include "worker.hh" #include "builtins.hh" #include "builtins/buildenv.hh" #include "path-references.hh" #include "finally.hh" #include "util.hh" #include "archive.hh" #include "git.hh" #include "compression.hh" #include "daemon.hh" #include "topo-sort.hh" #include "callback.hh" #include "json-utils.hh" #include "current-process.hh" #include "child.hh" #include "unix-domain-socket.hh" #include "posix-fs-canonicalise.hh" #include "posix-source-accessor.hh" #include <regex> #include <queue> #include <sys/un.h> #include <fcntl.h> #include <termios.h> #include <unistd.h> #include <sys/mman.h> #include <sys/resource.h> #include <sys/socket.h> #if HAVE_STATVFS #include <sys/statvfs.h> #endif /* Includes required for chroot support. */ #if __linux__ # include "fchmodat2-compat.hh" # include <sys/ioctl.h> # include <net/if.h> # include <netinet/ip.h> # include <sys/mman.h> # include <sched.h> # include <sys/param.h> # include <sys/mount.h> # include <sys/syscall.h> # include "namespaces.hh" # if HAVE_SECCOMP # include <seccomp.h> # endif # define pivot_root(new_root, put_old) (syscall(SYS_pivot_root, new_root, put_old)) # include "cgroup.hh" # include "personality.hh" #endif #if __APPLE__ #include <spawn.h> #include <sys/sysctl.h> #include <sandbox.h> /* This definition is undocumented but depended upon by all major browsers. */ extern "C" int sandbox_init_with_parameters(const char *profile, uint64_t flags, const char *const parameters[], char **errorbuf); #endif #include <pwd.h> #include <grp.h> #include <iostream> #include "strings.hh" #include "signals.hh" namespace nix { void handleDiffHook( uid_t uid, uid_t gid, const Path & tryA, const Path & tryB, const Path & drvPath, const Path & tmpDir) { auto & diffHookOpt = settings.diffHook.get(); if (diffHookOpt && settings.runDiffHook) { auto & diffHook = *diffHookOpt; try { auto diffRes = runProgram(RunOptions { .program = diffHook, .lookupPath = true, .args = {tryA, tryB, drvPath, tmpDir}, .uid = uid, .gid = gid, .chdir = "/" }); if (!statusOk(diffRes.first)) throw ExecError(diffRes.first, "diff-hook program '%1%' %2%", diffHook, statusToString(diffRes.first)); if (diffRes.second != "") printError(chomp(diffRes.second)); } catch (Error & error) { ErrorInfo ei = error.info(); // FIXME: wrap errors. ei.msg = HintFmt("diff hook execution failed: %s", ei.msg.str()); logError(ei); } } } const Path LocalDerivationGoal::homeDir = "/homeless-shelter"; LocalDerivationGoal::~LocalDerivationGoal() { /* Careful: we should never ever throw an exception from a destructor. */ try { deleteTmpDir(false); } catch (...) { ignoreExceptionInDestructor(); } try { killChild(); } catch (...) { ignoreExceptionInDestructor(); } try { stopDaemon(); } catch (...) { ignoreExceptionInDestructor(); } } inline bool LocalDerivationGoal::needsHashRewrite() { #if __linux__ return !useChroot; #else /* Darwin requires hash rewriting even when sandboxing is enabled. */ return true; #endif } LocalStore & LocalDerivationGoal::getLocalStore() { auto p = dynamic_cast<LocalStore *>(&worker.store); assert(p); return *p; } void LocalDerivationGoal::killChild() { if (pid != -1) { worker.childTerminated(this); /* If we're using a build user, then there is a tricky race condition: if we kill the build user before the child has done its setuid() to the build user uid, then it won't be killed, and we'll potentially lock up in pid.wait(). So also send a conventional kill to the child. */ ::kill(-pid, SIGKILL); /* ignore the result */ killSandbox(true); pid.wait(); } DerivationGoal::killChild(); } void LocalDerivationGoal::killSandbox(bool getStats) { if (cgroup) { #if __linux__ auto stats = destroyCgroup(*cgroup); if (getStats) { buildResult.cpuUser = stats.cpuUser; buildResult.cpuSystem = stats.cpuSystem; } #else unreachable(); #endif } else if (buildUser) { auto uid = buildUser->getUID(); assert(uid != 0); killUser(uid); } } Goal::Co LocalDerivationGoal::tryLocalBuild() { #if __APPLE__ additionalSandboxProfile = parsedDrv->getStringAttr("__sandboxProfile").value_or(""); #endif unsigned int curBuilds = worker.getNrLocalBuilds(); if (curBuilds >= settings.maxBuildJobs) { worker.waitForBuildSlot(shared_from_this()); outputLocks.unlock(); co_await Suspend{}; co_return tryToBuild(); } assert(derivationType); /* Are we doing a chroot build? */ { auto noChroot = parsedDrv->getBoolAttr("__noChroot"); if (settings.sandboxMode == smEnabled) { if (noChroot) throw Error("derivation '%s' has '__noChroot' set, " "but that's not allowed when 'sandbox' is 'true'", worker.store.printStorePath(drvPath)); #if __APPLE__ if (additionalSandboxProfile != "") throw Error("derivation '%s' specifies a sandbox profile, " "but this is only allowed when 'sandbox' is 'relaxed'", worker.store.printStorePath(drvPath)); #endif useChroot = true; } else if (settings.sandboxMode == smDisabled) useChroot = false; else if (settings.sandboxMode == smRelaxed) useChroot = derivationType->isSandboxed() && !noChroot; } auto & localStore = getLocalStore(); if (localStore.storeDir != localStore.realStoreDir.get()) { #if __linux__ useChroot = true; #else throw Error("building using a diverted store is not supported on this platform"); #endif } #if __linux__ if (useChroot) { if (!mountAndPidNamespacesSupported()) { if (!settings.sandboxFallback) throw Error("this system does not support the kernel namespaces that are required for sandboxing; use '--no-sandbox' to disable sandboxing"); debug("auto-disabling sandboxing because the prerequisite namespaces are not available"); useChroot = false; } } #endif if (useBuildUsers()) { if (!buildUser) buildUser = acquireUserLock(parsedDrv->useUidRange() ? 65536 : 1, useChroot); if (!buildUser) { if (!actLock) actLock = std::make_unique<Activity>(*logger, lvlWarn, actBuildWaiting, fmt("waiting for a free build user ID for '%s'", Magenta(worker.store.printStorePath(drvPath)))); worker.waitForAWhile(shared_from_this()); co_await Suspend{}; co_return tryLocalBuild(); } } actLock.reset(); try { /* Okay, we have to build. */ startBuilder(); } catch (BuildError & e) { outputLocks.unlock(); buildUser.reset(); worker.permanentFailure = true; co_return done(BuildResult::InputRejected, {}, std::move(e)); } started(); co_await Suspend{}; // after EOF on child co_return buildDone(); } static void chmod_(const Path & path, mode_t mode) { if (chmod(path.c_str(), mode) == -1) throw SysError("setting permissions on '%s'", path); } /* Move/rename path 'src' to 'dst'. Temporarily make 'src' writable if it's a directory and we're not root (to be able to update the directory's parent link ".."). */ static void movePath(const Path & src, const Path & dst) { auto st = lstat(src); bool changePerm = (geteuid() && S_ISDIR(st.st_mode) && !(st.st_mode & S_IWUSR)); if (changePerm) chmod_(src, st.st_mode | S_IWUSR); std::filesystem::rename(src, dst); if (changePerm) chmod_(dst, st.st_mode); } extern void replaceValidPath(const Path & storePath, const Path & tmpPath); int LocalDerivationGoal::getChildStatus() { return hook ? DerivationGoal::getChildStatus() : pid.kill(); } void LocalDerivationGoal::closeReadPipes() { if (hook) { DerivationGoal::closeReadPipes(); } else builderOut.close(); } void LocalDerivationGoal::cleanupHookFinally() { /* Release the build user at the end of this function. We don't do it right away because we don't want another build grabbing this uid and then messing around with our output. */ buildUser.reset(); } void LocalDerivationGoal::cleanupPreChildKill() { sandboxMountNamespace = -1; sandboxUserNamespace = -1; } void LocalDerivationGoal::cleanupPostChildKill() { /* When running under a build user, make sure that all processes running under that uid are gone. This is to prevent a malicious user from leaving behind a process that keeps files open and modifies them after they have been chown'ed to root. */ killSandbox(true); /* Terminate the recursive Nix daemon. */ stopDaemon(); } bool LocalDerivationGoal::cleanupDecideWhetherDiskFull() { bool diskFull = false; /* Heuristically check whether the build failure may have been caused by a disk full condition. We have no way of knowing whether the build actually got an ENOSPC. So instead, check if the disk is (nearly) full now. If so, we don't mark this build as a permanent failure. */ #if HAVE_STATVFS { auto & localStore = getLocalStore(); uint64_t required = 8ULL * 1024 * 1024; // FIXME: make configurable struct statvfs st; if (statvfs(localStore.realStoreDir.get().c_str(), &st) == 0 && (uint64_t) st.f_bavail * st.f_bsize < required) diskFull = true; if (statvfs(tmpDir.c_str(), &st) == 0 && (uint64_t) st.f_bavail * st.f_bsize < required) diskFull = true; } #endif deleteTmpDir(false); /* Move paths out of the chroot for easier debugging of build failures. */ if (useChroot && buildMode == bmNormal) for (auto & [_, status] : initialOutputs) { if (!status.known) continue; if (buildMode != bmCheck && status.known->isValid()) continue; auto p = worker.store.toRealPath(status.known->path); if (pathExists(chrootRootDir + p)) std::filesystem::rename((chrootRootDir + p), p); } return diskFull; } void LocalDerivationGoal::cleanupPostOutputsRegisteredModeCheck() { deleteTmpDir(true); } void LocalDerivationGoal::cleanupPostOutputsRegisteredModeNonCheck() { /* Delete unused redirected outputs (when doing hash rewriting). */ for (auto & i : redirectedOutputs) deletePath(worker.store.Store::toRealPath(i.second)); /* Delete the chroot (if we were using one). */ autoDelChroot.reset(); /* this runs the destructor */ cleanupPostOutputsRegisteredModeCheck(); } #if __linux__ static void doBind(const Path & source, const Path & target, bool optional = false) { debug("bind mounting '%1%' to '%2%'", source, target); auto bindMount = [&]() { if (mount(source.c_str(), target.c_str(), "", MS_BIND | MS_REC, 0) == -1) throw SysError("bind mount from '%1%' to '%2%' failed", source, target); }; auto maybeSt = maybeLstat(source); if (!maybeSt) { if (optional) return; else throw SysError("getting attributes of path '%1%'", source); } auto st = *maybeSt; if (S_ISDIR(st.st_mode)) { createDirs(target); bindMount(); } else if (S_ISLNK(st.st_mode)) { // Symlinks can (apparently) not be bind-mounted, so just copy it createDirs(dirOf(target)); copyFile( std::filesystem::path(source), std::filesystem::path(target), false); } else { createDirs(dirOf(target)); writeFile(target, ""); bindMount(); } }; #endif /** * Rethrow the current exception as a subclass of `Error`. */ static void rethrowExceptionAsError() { try { throw; } catch (Error &) { throw; } catch (std::exception & e) { throw Error(e.what()); } catch (...) { throw Error("unknown exception"); } } /** * Send the current exception to the parent in the format expected by * `LocalDerivationGoal::processSandboxSetupMessages()`. */ static void handleChildException(bool sendException) { try { rethrowExceptionAsError(); } catch (Error & e) { if (sendException) { writeFull(STDERR_FILENO, "\1\n"); FdSink sink(STDERR_FILENO); sink << e; sink.flush(); } else std::cerr << e.msg(); } } void LocalDerivationGoal::startBuilder() { if ((buildUser && buildUser->getUIDCount() != 1) #if __linux__ || settings.useCgroups #endif ) { #if __linux__ experimentalFeatureSettings.require(Xp::Cgroups); /* If we're running from the daemon, then this will return the root cgroup of the service. Otherwise, it will return the current cgroup. */ auto rootCgroup = getRootCgroup(); auto cgroupFS = getCgroupFS(); if (!cgroupFS) throw Error("cannot determine the cgroups file system"); auto rootCgroupPath = canonPath(*cgroupFS + "/" + rootCgroup); if (!pathExists(rootCgroupPath)) throw Error("expected cgroup directory '%s'", rootCgroupPath); static std::atomic<unsigned int> counter{0}; cgroup = buildUser ? fmt("%s/nix-build-uid-%d", rootCgroupPath, buildUser->getUID()) : fmt("%s/nix-build-pid-%d-%d", rootCgroupPath, getpid(), counter++); debug("using cgroup '%s'", *cgroup); /* When using a build user, record the cgroup we used for that user so that if we got interrupted previously, we can kill any left-over cgroup first. */ if (buildUser) { auto cgroupsDir = settings.nixStateDir + "/cgroups"; createDirs(cgroupsDir); auto cgroupFile = fmt("%s/%d", cgroupsDir, buildUser->getUID()); if (pathExists(cgroupFile)) { auto prevCgroup = readFile(cgroupFile); destroyCgroup(prevCgroup); } writeFile(cgroupFile, *cgroup); } #else throw Error("cgroups are not supported on this platform"); #endif } /* Make sure that no other processes are executing under the sandbox uids. This must be done before any chownToBuilder() calls. */ killSandbox(false); /* Right platform? */ if (!parsedDrv->canBuildLocally(worker.store)) throw Error("a '%s' with features {%s} is required to build '%s', but I am a '%s' with features {%s}", drv->platform, concatStringsSep(", ", parsedDrv->getRequiredSystemFeatures()), worker.store.printStorePath(drvPath), settings.thisSystem, concatStringsSep<StringSet>(", ", worker.store.systemFeatures)); /* Create a temporary directory where the build will take place. */ topTmpDir = createTempDir(settings.buildDir.get().value_or(""), "nix-build-" + std::string(drvPath.name()), false, false, 0700); #if __APPLE__ if (false) { #else if (useChroot) { #endif /* If sandboxing is enabled, put the actual TMPDIR underneath an inaccessible root-owned directory, to prevent outside access. On macOS, we don't use an actual chroot, so this isn't possible. Any mitigation along these lines would have to be done directly in the sandbox profile. */ tmpDir = topTmpDir + "/build"; createDir(tmpDir, 0700); } else { tmpDir = topTmpDir; } chownToBuilder(tmpDir); for (auto & [outputName, status] : initialOutputs) { /* Set scratch path we'll actually use during the build. If we're not doing a chroot build, but we have some valid output paths. Since we can't just overwrite or delete them, we have to do hash rewriting: i.e. in the environment/arguments passed to the build, we replace the hashes of the valid outputs with unique dummy strings; after the build, we discard the redirected outputs corresponding to the valid outputs, and rewrite the contents of the new outputs to replace the dummy strings with the actual hashes. */ auto scratchPath = !status.known ? makeFallbackPath(outputName) : !needsHashRewrite() /* Can always use original path in sandbox */ ? status.known->path : !status.known->isPresent() /* If path doesn't yet exist can just use it */ ? status.known->path : buildMode != bmRepair && !status.known->isValid() /* If we aren't repairing we'll delete a corrupted path, so we can use original path */ ? status.known->path : /* If we are repairing or the path is totally valid, we'll need to use a temporary path */ makeFallbackPath(status.known->path); scratchOutputs.insert_or_assign(outputName, scratchPath); /* Substitute output placeholders with the scratch output paths. We'll use during the build. */ inputRewrites[hashPlaceholder(outputName)] = worker.store.printStorePath(scratchPath); /* Additional tasks if we know the final path a priori. */ if (!status.known) continue; auto fixedFinalPath = status.known->path; /* Additional tasks if the final and scratch are both known and differ. */ if (fixedFinalPath == scratchPath) continue; /* Ensure scratch path is ours to use. */ deletePath(worker.store.printStorePath(scratchPath)); /* Rewrite and unrewrite paths */ { std::string h1 { fixedFinalPath.hashPart() }; std::string h2 { scratchPath.hashPart() }; inputRewrites[h1] = h2; } redirectedOutputs.insert_or_assign(std::move(fixedFinalPath), std::move(scratchPath)); } /* Construct the environment passed to the builder. */ initEnv(); writeStructuredAttrs(); /* Handle exportReferencesGraph(), if set. */ if (!parsedDrv->getStructuredAttrs()) { /* The `exportReferencesGraph' feature allows the references graph to be passed to a builder. This attribute should be a list of pairs [name1 path1 name2 path2 ...]. The references graph of each `pathN' will be stored in a text file `nameN' in the temporary build directory. The text files have the format used by `nix-store --register-validity'. However, the deriver fields are left empty. */ auto s = getOr(drv->env, "exportReferencesGraph", ""); Strings ss = tokenizeString<Strings>(s); if (ss.size() % 2 != 0) throw BuildError("odd number of tokens in 'exportReferencesGraph': '%1%'", s); for (Strings::iterator i = ss.begin(); i != ss.end(); ) { auto fileName = *i++; static std::regex regex("[A-Za-z_][A-Za-z0-9_.-]*"); if (!std::regex_match(fileName, regex)) throw Error("invalid file name '%s' in 'exportReferencesGraph'", fileName); auto storePathS = *i++; if (!worker.store.isInStore(storePathS)) throw BuildError("'exportReferencesGraph' contains a non-store path '%1%'", storePathS); auto storePath = worker.store.toStorePath(storePathS).first; /* Write closure info to <fileName>. */ writeFile(tmpDir + "/" + fileName, worker.store.makeValidityRegistration( worker.store.exportReferences({storePath}, inputPaths), false, false)); } } if (useChroot) { /* Allow a user-configurable set of directories from the host file system. */ pathsInChroot.clear(); for (auto i : settings.sandboxPaths.get()) { if (i.empty()) continue; bool optional = false; if (i[i.size() - 1] == '?') { optional = true; i.pop_back(); } size_t p = i.find('='); if (p == std::string::npos) pathsInChroot[i] = {i, optional}; else pathsInChroot[i.substr(0, p)] = {i.substr(p + 1), optional}; } if (hasPrefix(worker.store.storeDir, tmpDirInSandbox)) { throw Error("`sandbox-build-dir` must not contain the storeDir"); } pathsInChroot[tmpDirInSandbox] = tmpDir; /* Add the closure of store paths to the chroot. */ StorePathSet closure; for (auto & i : pathsInChroot) try { if (worker.store.isInStore(i.second.source)) worker.store.computeFSClosure(worker.store.toStorePath(i.second.source).first, closure); } catch (InvalidPath & e) { } catch (Error & e) { e.addTrace({}, "while processing 'sandbox-paths'"); throw; } for (auto & i : closure) { auto p = worker.store.printStorePath(i); pathsInChroot.insert_or_assign(p, p); } PathSet allowedPaths = settings.allowedImpureHostPrefixes; /* This works like the above, except on a per-derivation level */ auto impurePaths = parsedDrv->getStringsAttr("__impureHostDeps").value_or(Strings()); for (auto & i : impurePaths) { bool found = false; /* Note: we're not resolving symlinks here to prevent giving a non-root user info about inaccessible files. */ Path canonI = canonPath(i); /* If only we had a trie to do this more efficiently :) luckily, these are generally going to be pretty small */ for (auto & a : allowedPaths) { Path canonA = canonPath(a); if (canonI == canonA || isInDir(canonI, canonA)) { found = true; break; } } if (!found) throw Error("derivation '%s' requested impure path '%s', but it was not in allowed-impure-host-deps", worker.store.printStorePath(drvPath), i); /* Allow files in __impureHostDeps to be missing; e.g. macOS 11+ has no /usr/lib/libSystem*.dylib */ pathsInChroot[i] = {i, true}; } #if __linux__ /* Create a temporary directory in which we set up the chroot environment using bind-mounts. We put it in the Nix store so that the build outputs can be moved efficiently from the chroot to their final location. */ chrootParentDir = worker.store.Store::toRealPath(drvPath) + ".chroot"; deletePath(chrootParentDir); /* Clean up the chroot directory automatically. */ autoDelChroot = std::make_shared<AutoDelete>(chrootParentDir); printMsg(lvlChatty, "setting up chroot environment in '%1%'", chrootParentDir); if (mkdir(chrootParentDir.c_str(), 0700) == -1) throw SysError("cannot create '%s'", chrootRootDir); chrootRootDir = chrootParentDir + "/root"; if (mkdir(chrootRootDir.c_str(), buildUser && buildUser->getUIDCount() != 1 ? 0755 : 0750) == -1) throw SysError("cannot create '%1%'", chrootRootDir); if (buildUser && chown(chrootRootDir.c_str(), buildUser->getUIDCount() != 1 ? buildUser->getUID() : 0, buildUser->getGID()) == -1) throw SysError("cannot change ownership of '%1%'", chrootRootDir); /* Create a writable /tmp in the chroot. Many builders need this. (Of course they should really respect $TMPDIR instead.) */ Path chrootTmpDir = chrootRootDir + "/tmp"; createDirs(chrootTmpDir); chmod_(chrootTmpDir, 01777); /* Create a /etc/passwd with entries for the build user and the nobody account. The latter is kind of a hack to support Samba-in-QEMU. */ createDirs(chrootRootDir + "/etc"); if (parsedDrv->useUidRange()) chownToBuilder(chrootRootDir + "/etc"); if (parsedDrv->useUidRange() && (!buildUser || buildUser->getUIDCount() < 65536)) throw Error("feature 'uid-range' requires the setting '%s' to be enabled", settings.autoAllocateUids.name); /* Declare the build user's group so that programs get a consistent view of the system (e.g., "id -gn"). */ writeFile(chrootRootDir + "/etc/group", fmt("root:x:0:\n" "nixbld:!:%1%:\n" "nogroup:x:65534:\n", sandboxGid())); /* Create /etc/hosts with localhost entry. */ if (derivationType->isSandboxed()) writeFile(chrootRootDir + "/etc/hosts", "127.0.0.1 localhost\n::1 localhost\n"); /* Make the closure of the inputs available in the chroot, rather than the whole Nix store. This prevents any access to undeclared dependencies. Directories are bind-mounted, while other inputs are hard-linked (since only directories can be bind-mounted). !!! As an extra security precaution, make the fake Nix store only writable by the build user. */ Path chrootStoreDir = chrootRootDir + worker.store.storeDir; createDirs(chrootStoreDir); chmod_(chrootStoreDir, 01775); if (buildUser && chown(chrootStoreDir.c_str(), 0, buildUser->getGID()) == -1) throw SysError("cannot change ownership of '%1%'", chrootStoreDir); for (auto & i : inputPaths) { auto p = worker.store.printStorePath(i); Path r = worker.store.toRealPath(p); pathsInChroot.insert_or_assign(p, r); } /* If we're repairing, checking or rebuilding part of a multiple-outputs derivation, it's possible that we're rebuilding a path that is in settings.sandbox-paths (typically the dependencies of /bin/sh). Throw them out. */ for (auto & i : drv->outputsAndOptPaths(worker.store)) { /* If the name isn't known a priori (i.e. floating content-addressed derivation), the temporary location we use should be fresh. Freshness means it is impossible that the path is already in the sandbox, so we don't need to worry about removing it. */ if (i.second.second) pathsInChroot.erase(worker.store.printStorePath(*i.second.second)); } if (cgroup) { if (mkdir(cgroup->c_str(), 0755) != 0) throw SysError("creating cgroup '%s'", *cgroup); chownToBuilder(*cgroup); chownToBuilder(*cgroup + "/cgroup.procs"); chownToBuilder(*cgroup + "/cgroup.threads"); //chownToBuilder(*cgroup + "/cgroup.subtree_control"); } #else if (parsedDrv->useUidRange()) throw Error("feature 'uid-range' is not supported on this platform"); #if __APPLE__ /* We don't really have any parent prep work to do (yet?) All work happens in the child, instead. */ #else throw Error("sandboxing builds is not supported on this platform"); #endif #endif } else { if (parsedDrv->useUidRange()) throw Error("feature 'uid-range' is only supported in sandboxed builds"); } if (needsHashRewrite() && pathExists(homeDir)) throw Error("home directory '%1%' exists; please remove it to assure purity of builds without sandboxing", homeDir); if (useChroot && settings.preBuildHook != "" && dynamic_cast<Derivation *>(drv.get())) { printMsg(lvlChatty, "executing pre-build hook '%1%'", settings.preBuildHook); auto args = useChroot ? Strings({worker.store.printStorePath(drvPath), chrootRootDir}) : Strings({ worker.store.printStorePath(drvPath) }); enum BuildHookState { stBegin, stExtraChrootDirs }; auto state = stBegin; auto lines = runProgram(settings.preBuildHook, false, args); auto lastPos = std::string::size_type{0}; for (auto nlPos = lines.find('\n'); nlPos != std::string::npos; nlPos = lines.find('\n', lastPos)) { auto line = lines.substr(lastPos, nlPos - lastPos); lastPos = nlPos + 1; if (state == stBegin) { if (line == "extra-sandbox-paths" || line == "extra-chroot-dirs") { state = stExtraChrootDirs; } else { throw Error("unknown pre-build hook command '%1%'", line); } } else if (state == stExtraChrootDirs) { if (line == "") { state = stBegin; } else { auto p = line.find('='); if (p == std::string::npos) pathsInChroot[line] = line; else pathsInChroot[line.substr(0, p)] = line.substr(p + 1); } } } } /* Fire up a Nix daemon to process recursive Nix calls from the builder. */ if (parsedDrv->getRequiredSystemFeatures().count("recursive-nix")) startDaemon(); /* Run the builder. */ printMsg(lvlChatty, "executing builder '%1%'", drv->builder); printMsg(lvlChatty, "using builder args '%1%'", concatStringsSep(" ", drv->args)); for (auto & i : drv->env) printMsg(lvlVomit, "setting builder env variable '%1%'='%2%'", i.first, i.second); /* Create the log file. */ Path logFile = openLogFile(); /* Create a pseudoterminal to get the output of the builder. */ builderOut = posix_openpt(O_RDWR | O_NOCTTY); if (!builderOut) throw SysError("opening pseudoterminal master"); // FIXME: not thread-safe, use ptsname_r std::string slaveName = ptsname(builderOut.get()); if (buildUser) { if (chmod(slaveName.c_str(), 0600)) throw SysError("changing mode of pseudoterminal slave"); if (chown(slaveName.c_str(), buildUser->getUID(), 0)) throw SysError("changing owner of pseudoterminal slave"); } #if __APPLE__ else { if (grantpt(builderOut.get())) throw SysError("granting access to pseudoterminal slave"); } #endif if (unlockpt(builderOut.get())) throw SysError("unlocking pseudoterminal"); /* Open the slave side of the pseudoterminal and use it as stderr. */ auto openSlave = [&]() { AutoCloseFD builderOut = open(slaveName.c_str(), O_RDWR | O_NOCTTY); if (!builderOut) throw SysError("opening pseudoterminal slave"); // Put the pt into raw mode to prevent \n -> \r\n translation. struct termios term; if (tcgetattr(builderOut.get(), &term)) throw SysError("getting pseudoterminal attributes"); cfmakeraw(&term); if (tcsetattr(builderOut.get(), TCSANOW, &term)) throw SysError("putting pseudoterminal into raw mode"); if (dup2(builderOut.get(), STDERR_FILENO) == -1) throw SysError("cannot pipe standard error into log file"); }; buildResult.startTime = time(0); /* Fork a child to build the package. */ #if __linux__ if (useChroot) { /* Set up private namespaces for the build: - The PID namespace causes the build to start as PID 1. Processes outside of the chroot are not visible to those on the inside, but processes inside the chroot are visible from the outside (though with different PIDs). - The private mount namespace ensures that all the bind mounts we do will only show up in this process and its children, and will disappear automatically when we're done. - The private network namespace ensures that the builder cannot talk to the outside world (or vice versa). It only has a private loopback interface. (Fixed-output derivations are not run in a private network namespace to allow functions like fetchurl to work.) - The IPC namespace prevents the builder from communicating with outside processes using SysV IPC mechanisms (shared memory, message queues, semaphores). It also ensures that all IPC objects are destroyed when the builder exits. - The UTS namespace ensures that builders see a hostname of localhost rather than the actual hostname. We use a helper process to do the clone() to work around clone() being broken in multi-threaded programs due to at-fork handlers not being run. Note that we use CLONE_PARENT to ensure that the real builder is parented to us. */ if (derivationType->isSandboxed()) privateNetwork = true; userNamespaceSync.create(); usingUserNamespace = userNamespacesSupported(); Pipe sendPid; sendPid.create(); Pid helper = startProcess([&]() { sendPid.readSide.close(); /* We need to open the slave early, before CLONE_NEWUSER. Otherwise we get EPERM when running as root. */ openSlave(); try { /* Drop additional groups here because we can't do it after we've created the new user namespace. */ if (setgroups(0, 0) == -1) { if (errno != EPERM) throw SysError("setgroups failed"); if (settings.requireDropSupplementaryGroups) throw Error("setgroups failed. Set the require-drop-supplementary-groups option to false to skip this step."); } ProcessOptions options; options.cloneFlags = CLONE_NEWPID | CLONE_NEWNS | CLONE_NEWIPC | CLONE_NEWUTS | CLONE_PARENT | SIGCHLD; if (privateNetwork) options.cloneFlags |= CLONE_NEWNET; if (usingUserNamespace) options.cloneFlags |= CLONE_NEWUSER; pid_t child = startProcess([&]() { runChild(); }, options); writeFull(sendPid.writeSide.get(), fmt("%d\n", child)); _exit(0); } catch (...) { handleChildException(true); _exit(1); } }); sendPid.writeSide.close(); if (helper.wait() != 0) { processSandboxSetupMessages(); // Only reached if the child process didn't send an exception. throw Error("unable to start build process"); } userNamespaceSync.readSide = -1; /* Close the write side to prevent runChild() from hanging reading from this. */ Finally cleanup([&]() { userNamespaceSync.writeSide = -1; }); auto ss = tokenizeString<std::vector<std::string>>(readLine(sendPid.readSide.get())); assert(ss.size() == 1); pid = string2Int<pid_t>(ss[0]).value(); if (usingUserNamespace) { /* Set the UID/GID mapping of the builder's user namespace such that the sandbox user maps to the build user, or to the calling user (if build users are disabled). */ uid_t hostUid = buildUser ? buildUser->getUID() : getuid(); uid_t hostGid = buildUser ? buildUser->getGID() : getgid(); uid_t nrIds = buildUser ? buildUser->getUIDCount() : 1; writeFile("/proc/" + std::to_string(pid) + "/uid_map", fmt("%d %d %d", sandboxUid(), hostUid, nrIds)); if (!buildUser || buildUser->getUIDCount() == 1) writeFile("/proc/" + std::to_string(pid) + "/setgroups", "deny"); writeFile("/proc/" + std::to_string(pid) + "/gid_map", fmt("%d %d %d", sandboxGid(), hostGid, nrIds)); } else { debug("note: not using a user namespace"); if (!buildUser) throw Error("cannot perform a sandboxed build because user namespaces are not enabled; check /proc/sys/user/max_user_namespaces"); } /* Now that we now the sandbox uid, we can write /etc/passwd. */ writeFile(chrootRootDir + "/etc/passwd", fmt( "root:x:0:0:Nix build user:%3%:/noshell\n" "nixbld:x:%1%:%2%:Nix build user:%3%:/noshell\n" "nobody:x:65534:65534:Nobody:/:/noshell\n", sandboxUid(), sandboxGid(), settings.sandboxBuildDir)); /* Save the mount- and user namespace of the child. We have to do this *before* the child does a chroot. */ sandboxMountNamespace = open(fmt("/proc/%d/ns/mnt", (pid_t) pid).c_str(), O_RDONLY); if (sandboxMountNamespace.get() == -1) throw SysError("getting sandbox mount namespace"); if (usingUserNamespace) { sandboxUserNamespace = open(fmt("/proc/%d/ns/user", (pid_t) pid).c_str(), O_RDONLY); if (sandboxUserNamespace.get() == -1) throw SysError("getting sandbox user namespace"); } /* Move the child into its own cgroup. */ if (cgroup) writeFile(*cgroup + "/cgroup.procs", fmt("%d", (pid_t) pid)); /* Signal the builder that we've updated its user namespace. */ writeFull(userNamespaceSync.writeSide.get(), "1"); } else #endif { pid = startProcess([&]() { openSlave(); runChild(); }); } /* parent */ pid.setSeparatePG(true); worker.childStarted(shared_from_this(), {builderOut.get()}, true, true); processSandboxSetupMessages(); } void LocalDerivationGoal::processSandboxSetupMessages() { std::vector<std::string> msgs; while (true) { std::string msg = [&]() { try { return readLine(builderOut.get()); } catch (Error & e) { auto status = pid.wait(); e.addTrace({}, "while waiting for the build environment for '%s' to initialize (%s, previous messages: %s)", worker.store.printStorePath(drvPath), statusToString(status), concatStringsSep("|", msgs)); throw; } }(); if (msg.substr(0, 1) == "\2") break; if (msg.substr(0, 1) == "\1") { FdSource source(builderOut.get()); auto ex = readError(source); ex.addTrace({}, "while setting up the build environment"); throw ex; } debug("sandbox setup: " + msg); msgs.push_back(std::move(msg)); } } void LocalDerivationGoal::initTmpDir() { /* In a sandbox, for determinism, always use the same temporary directory. */ #if __linux__ tmpDirInSandbox = useChroot ? settings.sandboxBuildDir : tmpDir; #else tmpDirInSandbox = tmpDir; #endif /* In non-structured mode, add all bindings specified in the derivation via the environment, except those listed in the passAsFile attribute. Those are passed as file names pointing to temporary files containing the contents. Note that passAsFile is ignored in structure mode because it's not needed (attributes are not passed through the environment, so there is no size constraint). */ if (!parsedDrv->getStructuredAttrs()) { StringSet passAsFile = tokenizeString<StringSet>(getOr(drv->env, "passAsFile", "")); for (auto & i : drv->env) { if (passAsFile.find(i.first) == passAsFile.end()) { env[i.first] = i.second; } else { auto hash = hashString(HashAlgorithm::SHA256, i.first); std::string fn = ".attr-" + hash.to_string(HashFormat::Nix32, false); Path p = tmpDir + "/" + fn; writeFile(p, rewriteStrings(i.second, inputRewrites)); chownToBuilder(p); env[i.first + "Path"] = tmpDirInSandbox + "/" + fn; } } } /* For convenience, set an environment pointing to the top build directory. */ env["NIX_BUILD_TOP"] = tmpDirInSandbox; /* Also set TMPDIR and variants to point to this directory. */ env["TMPDIR"] = env["TEMPDIR"] = env["TMP"] = env["TEMP"] = tmpDirInSandbox; /* Explicitly set PWD to prevent problems with chroot builds. In particular, dietlibc cannot figure out the cwd because the inode of the current directory doesn't appear in .. (because getdents returns the inode of the mount point). */ env["PWD"] = tmpDirInSandbox; } void LocalDerivationGoal::initEnv() { env.clear(); /* Most shells initialise PATH to some default (/bin:/usr/bin:...) when PATH is not set. We don't want this, so we fill it in with some dummy value. */ env["PATH"] = "/path-not-set"; /* Set HOME to a non-existing path to prevent certain programs from using /etc/passwd (or NIS, or whatever) to locate the home directory (for example, wget looks for ~/.wgetrc). I.e., these tools use /etc/passwd if HOME is not set, but they will just assume that the settings file they are looking for does not exist if HOME is set but points to some non-existing path. */ env["HOME"] = homeDir; /* Tell the builder where the Nix store is. Usually they shouldn't care, but this is useful for purity checking (e.g., the compiler or linker might only want to accept paths to files in the store or in the build directory). */ env["NIX_STORE"] = worker.store.storeDir; /* The maximum number of cores to utilize for parallel building. */ env["NIX_BUILD_CORES"] = fmt("%d", settings.buildCores); initTmpDir(); /* Compatibility hack with Nix <= 0.7: if this is a fixed-output derivation, tell the builder, so that for instance `fetchurl' can skip checking the output. On older Nixes, this environment variable won't be set, so `fetchurl' will do the check. */ if (derivationType->isFixed()) env["NIX_OUTPUT_CHECKED"] = "1"; /* *Only* if this is a fixed-output derivation, propagate the values of the environment variables specified in the `impureEnvVars' attribute to the builder. This allows for instance environment variables for proxy configuration such as `http_proxy' to be easily passed to downloaders like `fetchurl'. Passing such environment variables from the caller to the builder is generally impure, but the output of fixed-output derivations is by definition pure (since we already know the cryptographic hash of the output). */ if (!derivationType->isSandboxed()) { auto & impureEnv = settings.impureEnv.get(); if (!impureEnv.empty()) experimentalFeatureSettings.require(Xp::ConfigurableImpureEnv); for (auto & i : parsedDrv->getStringsAttr("impureEnvVars").value_or(Strings())) { auto envVar = impureEnv.find(i); if (envVar != impureEnv.end()) { env[i] = envVar->second; } else { env[i] = getEnv(i).value_or(""); } } } /* Currently structured log messages piggyback on stderr, but we may change that in the future. So tell the builder which file descriptor to use for that. */ env["NIX_LOG_FD"] = "2"; /* Trigger colored output in various tools. */ env["TERM"] = "xterm-256color"; } void LocalDerivationGoal::writeStructuredAttrs() { if (auto structAttrsJson = parsedDrv->prepareStructuredAttrs(worker.store, inputPaths)) { auto json = structAttrsJson.value(); nlohmann::json rewritten; for (auto & [i, v] : json["outputs"].get<nlohmann::json::object_t>()) { /* The placeholder must have a rewrite, so we use it to cover both the cases where we know or don't know the output path ahead of time. */ rewritten[i] = rewriteStrings((std::string) v, inputRewrites); } json["outputs"] = rewritten; auto jsonSh = writeStructuredAttrsShell(json); writeFile(tmpDir + "/.attrs.sh", rewriteStrings(jsonSh, inputRewrites)); chownToBuilder(tmpDir + "/.attrs.sh"); env["NIX_ATTRS_SH_FILE"] = tmpDirInSandbox + "/.attrs.sh"; writeFile(tmpDir + "/.attrs.json", rewriteStrings(json.dump(), inputRewrites)); chownToBuilder(tmpDir + "/.attrs.json"); env["NIX_ATTRS_JSON_FILE"] = tmpDirInSandbox + "/.attrs.json"; } } static StorePath pathPartOfReq(const SingleDerivedPath & req) { return std::visit(overloaded { [&](const SingleDerivedPath::Opaque & bo) { return bo.path; }, [&](const SingleDerivedPath::Built & bfd) { return pathPartOfReq(*bfd.drvPath); }, }, req.raw()); } static StorePath pathPartOfReq(const DerivedPath & req) { return std::visit(overloaded { [&](const DerivedPath::Opaque & bo) { return bo.path; }, [&](const DerivedPath::Built & bfd) { return pathPartOfReq(*bfd.drvPath); }, }, req.raw()); } bool LocalDerivationGoal::isAllowed(const DerivedPath & req) { return this->isAllowed(pathPartOfReq(req)); } struct RestrictedStoreConfig : virtual LocalFSStoreConfig { using LocalFSStoreConfig::LocalFSStoreConfig; const std::string name() override { return "Restricted Store"; } }; /* A wrapper around LocalStore that only allows building/querying of paths that are in the input closures of the build or were added via recursive Nix calls. */ struct RestrictedStore : public virtual RestrictedStoreConfig, public virtual IndirectRootStore, public virtual GcStore { ref<LocalStore> next; LocalDerivationGoal & goal; RestrictedStore(const Params & params, ref<LocalStore> next, LocalDerivationGoal & goal) : StoreConfig(params) , LocalFSStoreConfig(params) , RestrictedStoreConfig(params) , Store(params) , LocalFSStore(params) , next(next), goal(goal) { } Path getRealStoreDir() override { return next->realStoreDir; } std::string getUri() override { return next->getUri(); } StorePathSet queryAllValidPaths() override { StorePathSet paths; for (auto & p : goal.inputPaths) paths.insert(p); for (auto & p : goal.addedPaths) paths.insert(p); return paths; } void queryPathInfoUncached(const StorePath & path, Callback<std::shared_ptr<const ValidPathInfo>> callback) noexcept override { if (goal.isAllowed(path)) { try { /* Censor impure information. */ auto info = std::make_shared<ValidPathInfo>(*next->queryPathInfo(path)); info->deriver.reset(); info->registrationTime = 0; info->ultimate = false; info->sigs.clear(); callback(info); } catch (InvalidPath &) { callback(nullptr); } } else callback(nullptr); }; void queryReferrers(const StorePath & path, StorePathSet & referrers) override { } std::map<std::string, std::optional<StorePath>> queryPartialDerivationOutputMap( const StorePath & path, Store * evalStore = nullptr) override { if (!goal.isAllowed(path)) throw InvalidPath("cannot query output map for unknown path '%s' in recursive Nix", printStorePath(path)); return next->queryPartialDerivationOutputMap(path, evalStore); } std::optional<StorePath> queryPathFromHashPart(const std::string & hashPart) override { throw Error("queryPathFromHashPart"); } StorePath addToStore( std::string_view name, const SourcePath & srcPath, ContentAddressMethod method, HashAlgorithm hashAlgo, const StorePathSet & references, PathFilter & filter, RepairFlag repair) override { throw Error("addToStore"); } void addToStore(const ValidPathInfo & info, Source & narSource, RepairFlag repair = NoRepair, CheckSigsFlag checkSigs = CheckSigs) override { next->addToStore(info, narSource, repair, checkSigs); goal.addDependency(info.path); } StorePath addToStoreFromDump( Source & dump, std::string_view name, FileSerialisationMethod dumpMethod, ContentAddressMethod hashMethod, HashAlgorithm hashAlgo, const StorePathSet & references, RepairFlag repair) override { auto path = next->addToStoreFromDump(dump, name, dumpMethod, hashMethod, hashAlgo, references, repair); goal.addDependency(path); return path; } void narFromPath(const StorePath & path, Sink & sink) override { if (!goal.isAllowed(path)) throw InvalidPath("cannot dump unknown path '%s' in recursive Nix", printStorePath(path)); LocalFSStore::narFromPath(path, sink); } void ensurePath(const StorePath & path) override { if (!goal.isAllowed(path)) throw InvalidPath("cannot substitute unknown path '%s' in recursive Nix", printStorePath(path)); /* Nothing to be done; 'path' must already be valid. */ } void registerDrvOutput(const Realisation & info) override // XXX: This should probably be allowed as a no-op if the realisation // corresponds to an allowed derivation { throw Error("registerDrvOutput"); } void queryRealisationUncached(const DrvOutput & id, Callback<std::shared_ptr<const Realisation>> callback) noexcept override // XXX: This should probably be allowed if the realisation corresponds to // an allowed derivation { if (!goal.isAllowed(id)) callback(nullptr); next->queryRealisation(id, std::move(callback)); } void buildPaths(const std::vector<DerivedPath> & paths, BuildMode buildMode, std::shared_ptr<Store> evalStore) override { for (auto & result : buildPathsWithResults(paths, buildMode, evalStore)) if (!result.success()) result.rethrow(); } std::vector<KeyedBuildResult> buildPathsWithResults( const std::vector<DerivedPath> & paths, BuildMode buildMode = bmNormal, std::shared_ptr<Store> evalStore = nullptr) override { assert(!evalStore); if (buildMode != bmNormal) throw Error("unsupported build mode"); StorePathSet newPaths; std::set<Realisation> newRealisations; for (auto & req : paths) { if (!goal.isAllowed(req)) throw InvalidPath("cannot build '%s' in recursive Nix because path is unknown", req.to_string(*next)); } auto results = next->buildPathsWithResults(paths, buildMode); for (auto & result : results) { for (auto & [outputName, output] : result.builtOutputs) { newPaths.insert(output.outPath); newRealisations.insert(output); } } StorePathSet closure; next->computeFSClosure(newPaths, closure); for (auto & path : closure) goal.addDependency(path); for (auto & real : Realisation::closure(*next, newRealisations)) goal.addedDrvOutputs.insert(real.id); return results; } BuildResult buildDerivation(const StorePath & drvPath, const BasicDerivation & drv, BuildMode buildMode = bmNormal) override { unsupported("buildDerivation"); } void addTempRoot(const StorePath & path) override { } void addIndirectRoot(const Path & path) override { } Roots findRoots(bool censor) override { return Roots(); } void collectGarbage(const GCOptions & options, GCResults & results) override { } void addSignatures(const StorePath & storePath, const StringSet & sigs) override { unsupported("addSignatures"); } void queryMissing(const std::vector<DerivedPath> & targets, StorePathSet & willBuild, StorePathSet & willSubstitute, StorePathSet & unknown, uint64_t & downloadSize, uint64_t & narSize) override { /* This is slightly impure since it leaks information to the client about what paths will be built/substituted or are already present. Probably not a big deal. */ std::vector<DerivedPath> allowed; for (auto & req : targets) { if (goal.isAllowed(req)) allowed.emplace_back(req); else unknown.insert(pathPartOfReq(req)); } next->queryMissing(allowed, willBuild, willSubstitute, unknown, downloadSize, narSize); } virtual std::optional<std::string> getBuildLogExact(const StorePath & path) override { return std::nullopt; } virtual void addBuildLog(const StorePath & path, std::string_view log) override { unsupported("addBuildLog"); } std::optional<TrustedFlag> isTrustedClient() override { return NotTrusted; } }; void LocalDerivationGoal::startDaemon() { experimentalFeatureSettings.require(Xp::RecursiveNix); Store::Params params; params["path-info-cache-size"] = "0"; params["store"] = worker.store.storeDir; if (auto & optRoot = getLocalStore().rootDir.get()) params["root"] = *optRoot; params["state"] = "/no-such-path"; params["log"] = "/no-such-path"; auto store = make_ref<RestrictedStore>(params, ref<LocalStore>(std::dynamic_pointer_cast<LocalStore>(worker.store.shared_from_this())), *this); addedPaths.clear(); auto socketName = ".nix-socket"; Path socketPath = tmpDir + "/" + socketName; env["NIX_REMOTE"] = "unix://" + tmpDirInSandbox + "/" + socketName; daemonSocket = createUnixDomainSocket(socketPath, 0600); chownToBuilder(socketPath); daemonThread = std::thread([this, store]() { while (true) { /* Accept a connection. */ struct sockaddr_un remoteAddr; socklen_t remoteAddrLen = sizeof(remoteAddr); AutoCloseFD remote = accept(daemonSocket.get(), (struct sockaddr *) &remoteAddr, &remoteAddrLen); if (!remote) { if (errno == EINTR || errno == EAGAIN) continue; if (errno == EINVAL || errno == ECONNABORTED) break; throw SysError("accepting connection"); } unix::closeOnExec(remote.get()); debug("received daemon connection"); auto workerThread = std::thread([store, remote{std::move(remote)}]() { try { daemon::processConnection( store, FdSource(remote.get()), FdSink(remote.get()), NotTrusted, daemon::Recursive); debug("terminated daemon connection"); } catch (const Interrupted &) { debug("interrupted daemon connection"); } catch (SystemError &) { ignoreExceptionExceptInterrupt(); } }); daemonWorkerThreads.push_back(std::move(workerThread)); } debug("daemon shutting down"); }); } void LocalDerivationGoal::stopDaemon() { if (daemonSocket && shutdown(daemonSocket.get(), SHUT_RDWR) == -1) { // According to the POSIX standard, the 'shutdown' function should // return an ENOTCONN error when attempting to shut down a socket that // hasn't been connected yet. This situation occurs when the 'accept' // function is called on a socket without any accepted connections, // leaving the socket unconnected. While Linux doesn't seem to produce // an error for sockets that have only been accepted, more // POSIX-compliant operating systems like OpenBSD, macOS, and others do // return the ENOTCONN error. Therefore, we handle this error here to // avoid raising an exception for compliant behaviour. if (errno == ENOTCONN) { daemonSocket.close(); } else { throw SysError("shutting down daemon socket"); } } if (daemonThread.joinable()) daemonThread.join(); // FIXME: should prune worker threads more quickly. // FIXME: shutdown the client socket to speed up worker termination. for (auto & thread : daemonWorkerThreads) thread.join(); daemonWorkerThreads.clear(); // release the socket. daemonSocket.close(); } void LocalDerivationGoal::addDependency(const StorePath & path) { if (isAllowed(path)) return; addedPaths.insert(path); /* If we're doing a sandbox build, then we have to make the path appear in the sandbox. */ if (useChroot) { debug("materialising '%s' in the sandbox", worker.store.printStorePath(path)); #if __linux__ Path source = worker.store.Store::toRealPath(path); Path target = chrootRootDir + worker.store.printStorePath(path); if (pathExists(target)) { // There is a similar debug message in doBind, so only run it in this block to not have double messages. debug("bind-mounting %s -> %s", target, source); throw Error("store path '%s' already exists in the sandbox", worker.store.printStorePath(path)); } /* Bind-mount the path into the sandbox. This requires entering its mount namespace, which is not possible in multithreaded programs. So we do this in a child process.*/ Pid child(startProcess([&]() { if (usingUserNamespace && (setns(sandboxUserNamespace.get(), 0) == -1)) throw SysError("entering sandbox user namespace"); if (setns(sandboxMountNamespace.get(), 0) == -1) throw SysError("entering sandbox mount namespace"); doBind(source, target); _exit(0); })); int status = child.wait(); if (status != 0) throw Error("could not add path '%s' to sandbox", worker.store.printStorePath(path)); #else throw Error("don't know how to make path '%s' (produced by a recursive Nix call) appear in the sandbox", worker.store.printStorePath(path)); #endif } } void LocalDerivationGoal::chownToBuilder(const Path & path) { if (!buildUser) return; if (chown(path.c_str(), buildUser->getUID(), buildUser->getGID()) == -1) throw SysError("cannot change ownership of '%1%'", path); } void setupSeccomp() { #if __linux__ if (!settings.filterSyscalls) return; #if HAVE_SECCOMP scmp_filter_ctx ctx; if (!(ctx = seccomp_init(SCMP_ACT_ALLOW))) throw SysError("unable to initialize seccomp mode 2"); Finally cleanup([&]() { seccomp_release(ctx); }); constexpr std::string_view nativeSystem = SYSTEM; if (nativeSystem == "x86_64-linux" && seccomp_arch_add(ctx, SCMP_ARCH_X86) != 0) throw SysError("unable to add 32-bit seccomp architecture"); if (nativeSystem == "x86_64-linux" && seccomp_arch_add(ctx, SCMP_ARCH_X32) != 0) throw SysError("unable to add X32 seccomp architecture"); if (nativeSystem == "aarch64-linux" && seccomp_arch_add(ctx, SCMP_ARCH_ARM) != 0) printError("unable to add ARM seccomp architecture; this may result in spurious build failures if running 32-bit ARM processes"); if (nativeSystem == "mips64-linux" && seccomp_arch_add(ctx, SCMP_ARCH_MIPS) != 0) printError("unable to add mips seccomp architecture"); if (nativeSystem == "mips64-linux" && seccomp_arch_add(ctx, SCMP_ARCH_MIPS64N32) != 0) printError("unable to add mips64-*abin32 seccomp architecture"); if (nativeSystem == "mips64el-linux" && seccomp_arch_add(ctx, SCMP_ARCH_MIPSEL) != 0) printError("unable to add mipsel seccomp architecture"); if (nativeSystem == "mips64el-linux" && seccomp_arch_add(ctx, SCMP_ARCH_MIPSEL64N32) != 0) printError("unable to add mips64el-*abin32 seccomp architecture"); /* Prevent builders from creating setuid/setgid binaries. */ for (int perm : { S_ISUID, S_ISGID }) { if (seccomp_rule_add(ctx, SCMP_ACT_ERRNO(EPERM), SCMP_SYS(chmod), 1, SCMP_A1(SCMP_CMP_MASKED_EQ, (scmp_datum_t) perm, (scmp_datum_t) perm)) != 0) throw SysError("unable to add seccomp rule"); if (seccomp_rule_add(ctx, SCMP_ACT_ERRNO(EPERM), SCMP_SYS(fchmod), 1, SCMP_A1(SCMP_CMP_MASKED_EQ, (scmp_datum_t) perm, (scmp_datum_t) perm)) != 0) throw SysError("unable to add seccomp rule"); if (seccomp_rule_add(ctx, SCMP_ACT_ERRNO(EPERM), SCMP_SYS(fchmodat), 1, SCMP_A2(SCMP_CMP_MASKED_EQ, (scmp_datum_t) perm, (scmp_datum_t) perm)) != 0) throw SysError("unable to add seccomp rule"); if (seccomp_rule_add(ctx, SCMP_ACT_ERRNO(EPERM), NIX_SYSCALL_FCHMODAT2, 1, SCMP_A2(SCMP_CMP_MASKED_EQ, (scmp_datum_t) perm, (scmp_datum_t) perm)) != 0) throw SysError("unable to add seccomp rule"); } /* Prevent builders from using EAs or ACLs. Not all filesystems support these, and they're not allowed in the Nix store because they're not representable in the NAR serialisation. */ if (seccomp_rule_add(ctx, SCMP_ACT_ERRNO(ENOTSUP), SCMP_SYS(getxattr), 0) != 0 || seccomp_rule_add(ctx, SCMP_ACT_ERRNO(ENOTSUP), SCMP_SYS(lgetxattr), 0) != 0 || seccomp_rule_add(ctx, SCMP_ACT_ERRNO(ENOTSUP), SCMP_SYS(fgetxattr), 0) != 0 || seccomp_rule_add(ctx, SCMP_ACT_ERRNO(ENOTSUP), SCMP_SYS(setxattr), 0) != 0 || seccomp_rule_add(ctx, SCMP_ACT_ERRNO(ENOTSUP), SCMP_SYS(lsetxattr), 0) != 0 || seccomp_rule_add(ctx, SCMP_ACT_ERRNO(ENOTSUP), SCMP_SYS(fsetxattr), 0) != 0) throw SysError("unable to add seccomp rule"); if (seccomp_attr_set(ctx, SCMP_FLTATR_CTL_NNP, settings.allowNewPrivileges ? 0 : 1) != 0) throw SysError("unable to set 'no new privileges' seccomp attribute"); if (seccomp_load(ctx) != 0) throw SysError("unable to load seccomp BPF program"); #else throw Error( "seccomp is not supported on this platform; " "you can bypass this error by setting the option 'filter-syscalls' to false, but note that untrusted builds can then create setuid binaries!"); #endif #endif } void LocalDerivationGoal::runChild() { /* Warning: in the child we should absolutely not make any SQLite calls! */ bool sendException = true; try { /* child */ commonChildInit(); try { setupSeccomp(); } catch (...) { if (buildUser) throw; } bool setUser = true; /* Make the contents of netrc and the CA certificate bundle available to builtin:fetchurl (which may run under a different uid and/or in a sandbox). */ std::string netrcData; std::string caFileData; if (drv->isBuiltin() && drv->builder == "builtin:fetchurl") { try { netrcData = readFile(settings.netrcFile); } catch (SystemError &) { } try { caFileData = readFile(settings.caFile); } catch (SystemError &) { } } #if __linux__ if (useChroot) { userNamespaceSync.writeSide = -1; if (drainFD(userNamespaceSync.readSide.get()) != "1") throw Error("user namespace initialisation failed"); userNamespaceSync.readSide = -1; if (privateNetwork) { /* Initialise the loopback interface. */ AutoCloseFD fd(socket(PF_INET, SOCK_DGRAM, IPPROTO_IP)); if (!fd) throw SysError("cannot open IP socket"); struct ifreq ifr; strcpy(ifr.ifr_name, "lo"); ifr.ifr_flags = IFF_UP | IFF_LOOPBACK | IFF_RUNNING; if (ioctl(fd.get(), SIOCSIFFLAGS, &ifr) == -1) throw SysError("cannot set loopback interface flags"); } /* Set the hostname etc. to fixed values. */ char hostname[] = "localhost"; if (sethostname(hostname, sizeof(hostname)) == -1) throw SysError("cannot set host name"); char domainname[] = "(none)"; // kernel default if (setdomainname(domainname, sizeof(domainname)) == -1) throw SysError("cannot set domain name"); /* Make all filesystems private. This is necessary because subtrees may have been mounted as "shared" (MS_SHARED). (Systemd does this, for instance.) Even though we have a private mount namespace, mounting filesystems on top of a shared subtree still propagates outside of the namespace. Making a subtree private is local to the namespace, though, so setting MS_PRIVATE does not affect the outside world. */ if (mount(0, "/", 0, MS_PRIVATE | MS_REC, 0) == -1) throw SysError("unable to make '/' private"); /* Bind-mount chroot directory to itself, to treat it as a different filesystem from /, as needed for pivot_root. */ if (mount(chrootRootDir.c_str(), chrootRootDir.c_str(), 0, MS_BIND, 0) == -1) throw SysError("unable to bind mount '%1%'", chrootRootDir); /* Bind-mount the sandbox's Nix store onto itself so that we can mark it as a "shared" subtree, allowing bind mounts made in *this* mount namespace to be propagated into the child namespace created by the unshare(CLONE_NEWNS) call below. Marking chrootRootDir as MS_SHARED causes pivot_root() to fail with EINVAL. Don't know why. */ Path chrootStoreDir = chrootRootDir + worker.store.storeDir; if (mount(chrootStoreDir.c_str(), chrootStoreDir.c_str(), 0, MS_BIND, 0) == -1) throw SysError("unable to bind mount the Nix store", chrootStoreDir); if (mount(0, chrootStoreDir.c_str(), 0, MS_SHARED, 0) == -1) throw SysError("unable to make '%s' shared", chrootStoreDir); /* Set up a nearly empty /dev, unless the user asked to bind-mount the host /dev. */ Strings ss; if (pathsInChroot.find("/dev") == pathsInChroot.end()) { createDirs(chrootRootDir + "/dev/shm"); createDirs(chrootRootDir + "/dev/pts"); ss.push_back("/dev/full"); if (worker.store.systemFeatures.get().count("kvm") && pathExists("/dev/kvm")) ss.push_back("/dev/kvm"); ss.push_back("/dev/null"); ss.push_back("/dev/random"); ss.push_back("/dev/tty"); ss.push_back("/dev/urandom"); ss.push_back("/dev/zero"); createSymlink("/proc/self/fd", chrootRootDir + "/dev/fd"); createSymlink("/proc/self/fd/0", chrootRootDir + "/dev/stdin"); createSymlink("/proc/self/fd/1", chrootRootDir + "/dev/stdout"); createSymlink("/proc/self/fd/2", chrootRootDir + "/dev/stderr"); } /* Fixed-output derivations typically need to access the network, so give them access to /etc/resolv.conf and so on. */ if (!derivationType->isSandboxed()) { // Only use nss functions to resolve hosts and // services. Don’t use it for anything else that may // be configured for this system. This limits the // potential impurities introduced in fixed-outputs. writeFile(chrootRootDir + "/etc/nsswitch.conf", "hosts: files dns\nservices: files\n"); /* N.B. it is realistic that these paths might not exist. It happens when testing Nix building fixed-output derivations within a pure derivation. */ for (auto & path : { "/etc/resolv.conf", "/etc/services", "/etc/hosts" }) if (pathExists(path)) ss.push_back(path); if (settings.caFile != "" && pathExists(settings.caFile)) { Path caFile = settings.caFile; pathsInChroot.try_emplace("/etc/ssl/certs/ca-certificates.crt", canonPath(caFile, true), true); } } for (auto & i : ss) { // For backwards-compatibiliy, resolve all the symlinks in the // chroot paths auto canonicalPath = canonPath(i, true); pathsInChroot.emplace(i, canonicalPath); } /* Bind-mount all the directories from the "host" filesystem that we want in the chroot environment. */ for (auto & i : pathsInChroot) { if (i.second.source == "/proc") continue; // backwards compatibility #if HAVE_EMBEDDED_SANDBOX_SHELL if (i.second.source == "__embedded_sandbox_shell__") { static unsigned char sh[] = { #include "embedded-sandbox-shell.gen.hh" }; auto dst = chrootRootDir + i.first; createDirs(dirOf(dst)); writeFile(dst, std::string_view((const char *) sh, sizeof(sh))); chmod_(dst, 0555); } else #endif doBind(i.second.source, chrootRootDir + i.first, i.second.optional); } /* Bind a new instance of procfs on /proc. */ createDirs(chrootRootDir + "/proc"); if (mount("none", (chrootRootDir + "/proc").c_str(), "proc", 0, 0) == -1) throw SysError("mounting /proc"); /* Mount sysfs on /sys. */ if (buildUser && buildUser->getUIDCount() != 1) { createDirs(chrootRootDir + "/sys"); if (mount("none", (chrootRootDir + "/sys").c_str(), "sysfs", 0, 0) == -1) throw SysError("mounting /sys"); } /* Mount a new tmpfs on /dev/shm to ensure that whatever the builder puts in /dev/shm is cleaned up automatically. */ if (pathExists("/dev/shm") && mount("none", (chrootRootDir + "/dev/shm").c_str(), "tmpfs", 0, fmt("size=%s", settings.sandboxShmSize).c_str()) == -1) throw SysError("mounting /dev/shm"); /* Mount a new devpts on /dev/pts. Note that this requires the kernel to be compiled with CONFIG_DEVPTS_MULTIPLE_INSTANCES=y (which is the case if /dev/ptx/ptmx exists). */ if (pathExists("/dev/pts/ptmx") && !pathExists(chrootRootDir + "/dev/ptmx") && !pathsInChroot.count("/dev/pts")) { if (mount("none", (chrootRootDir + "/dev/pts").c_str(), "devpts", 0, "newinstance,mode=0620") == 0) { createSymlink("/dev/pts/ptmx", chrootRootDir + "/dev/ptmx"); /* Make sure /dev/pts/ptmx is world-writable. With some Linux versions, it is created with permissions 0. */ chmod_(chrootRootDir + "/dev/pts/ptmx", 0666); } else { if (errno != EINVAL) throw SysError("mounting /dev/pts"); doBind("/dev/pts", chrootRootDir + "/dev/pts"); doBind("/dev/ptmx", chrootRootDir + "/dev/ptmx"); } } /* Make /etc unwritable */ if (!parsedDrv->useUidRange()) chmod_(chrootRootDir + "/etc", 0555); /* Unshare this mount namespace. This is necessary because pivot_root() below changes the root of the mount namespace. This means that the call to setns() in addDependency() would hide the host's filesystem, making it impossible to bind-mount paths from the host Nix store into the sandbox. Therefore, we save the pre-pivot_root namespace in sandboxMountNamespace. Since we made /nix/store a shared subtree above, this allows addDependency() to make paths appear in the sandbox. */ if (unshare(CLONE_NEWNS) == -1) throw SysError("unsharing mount namespace"); /* Unshare the cgroup namespace. This means /proc/self/cgroup will show the child's cgroup as '/' rather than whatever it is in the parent. */ if (cgroup && unshare(CLONE_NEWCGROUP) == -1) throw SysError("unsharing cgroup namespace"); /* Do the chroot(). */ if (chdir(chrootRootDir.c_str()) == -1) throw SysError("cannot change directory to '%1%'", chrootRootDir); if (mkdir("real-root", 0500) == -1) throw SysError("cannot create real-root directory"); if (pivot_root(".", "real-root") == -1) throw SysError("cannot pivot old root directory onto '%1%'", (chrootRootDir + "/real-root")); if (chroot(".") == -1) throw SysError("cannot change root directory to '%1%'", chrootRootDir); if (umount2("real-root", MNT_DETACH) == -1) throw SysError("cannot unmount real root filesystem"); if (rmdir("real-root") == -1) throw SysError("cannot remove real-root directory"); /* Switch to the sandbox uid/gid in the user namespace, which corresponds to the build user or calling user in the parent namespace. */ if (setgid(sandboxGid()) == -1) throw SysError("setgid failed"); if (setuid(sandboxUid()) == -1) throw SysError("setuid failed"); setUser = false; } #endif if (chdir(tmpDirInSandbox.c_str()) == -1) throw SysError("changing into '%1%'", tmpDir); /* Close all other file descriptors. */ unix::closeExtraFDs(); #if __linux__ linux::setPersonality(drv->platform); #endif /* Disable core dumps by default. */ struct rlimit limit = { 0, RLIM_INFINITY }; setrlimit(RLIMIT_CORE, &limit); // FIXME: set other limits to deterministic values? /* Fill in the environment. */ Strings envStrs; for (auto & i : env) envStrs.push_back(rewriteStrings(i.first + "=" + i.second, inputRewrites)); /* If we are running in `build-users' mode, then switch to the user we allocated above. Make sure that we drop all root privileges. Note that above we have closed all file descriptors except std*, so that's safe. Also note that setuid() when run as root sets the real, effective and saved UIDs. */ if (setUser && buildUser) { /* Preserve supplementary groups of the build user, to allow admins to specify groups such as "kvm". */ auto gids = buildUser->getSupplementaryGIDs(); if (setgroups(gids.size(), gids.data()) == -1) throw SysError("cannot set supplementary groups of build user"); if (setgid(buildUser->getGID()) == -1 || getgid() != buildUser->getGID() || getegid() != buildUser->getGID()) throw SysError("setgid failed"); if (setuid(buildUser->getUID()) == -1 || getuid() != buildUser->getUID() || geteuid() != buildUser->getUID()) throw SysError("setuid failed"); } #if __APPLE__ /* This has to appear before import statements. */ std::string sandboxProfile = "(version 1)\n"; if (useChroot) { /* Lots and lots and lots of file functions freak out if they can't stat their full ancestry */ PathSet ancestry; /* We build the ancestry before adding all inputPaths to the store because we know they'll all have the same parents (the store), and there might be lots of inputs. This isn't particularly efficient... I doubt it'll be a bottleneck in practice */ for (auto & i : pathsInChroot) { Path cur = i.first; while (cur.compare("/") != 0) { cur = dirOf(cur); ancestry.insert(cur); } } /* And we want the store in there regardless of how empty pathsInChroot. We include the innermost path component this time, since it's typically /nix/store and we care about that. */ Path cur = worker.store.storeDir; while (cur.compare("/") != 0) { ancestry.insert(cur); cur = dirOf(cur); } /* Add all our input paths to the chroot */ for (auto & i : inputPaths) { auto p = worker.store.printStorePath(i); pathsInChroot[p] = p; } /* Violations will go to the syslog if you set this. Unfortunately the destination does not appear to be configurable */ if (settings.darwinLogSandboxViolations) { sandboxProfile += "(deny default)\n"; } else { sandboxProfile += "(deny default (with no-log))\n"; } sandboxProfile += #include "sandbox-defaults.sb" ; if (!derivationType->isSandboxed()) sandboxProfile += #include "sandbox-network.sb" ; /* Add the output paths we'll use at build-time to the chroot */ sandboxProfile += "(allow file-read* file-write* process-exec\n"; for (auto & [_, path] : scratchOutputs) sandboxProfile += fmt("\t(subpath \"%s\")\n", worker.store.printStorePath(path)); sandboxProfile += ")\n"; /* Our inputs (transitive dependencies and any impurities computed above) without file-write* allowed, access() incorrectly returns EPERM */ sandboxProfile += "(allow file-read* file-write* process-exec\n"; for (auto & i : pathsInChroot) { if (i.first != i.second.source) throw Error( "can't map '%1%' to '%2%': mismatched impure paths not supported on Darwin", i.first, i.second.source); std::string path = i.first; auto optSt = maybeLstat(path.c_str()); if (!optSt) { if (i.second.optional) continue; throw SysError("getting attributes of required path '%s", path); } if (S_ISDIR(optSt->st_mode)) sandboxProfile += fmt("\t(subpath \"%s\")\n", path); else sandboxProfile += fmt("\t(literal \"%s\")\n", path); } sandboxProfile += ")\n"; /* Allow file-read* on full directory hierarchy to self. Allows realpath() */ sandboxProfile += "(allow file-read*\n"; for (auto & i : ancestry) { sandboxProfile += fmt("\t(literal \"%s\")\n", i); } sandboxProfile += ")\n"; sandboxProfile += additionalSandboxProfile; } else sandboxProfile += #include "sandbox-minimal.sb" ; debug("Generated sandbox profile:"); debug(sandboxProfile); bool allowLocalNetworking = parsedDrv->getBoolAttr("__darwinAllowLocalNetworking"); /* The tmpDir in scope points at the temporary build directory for our derivation. Some packages try different mechanisms to find temporary directories, so we want to open up a broader place for them to put their files, if needed. */ Path globalTmpDir = canonPath(defaultTempDir(), true); /* They don't like trailing slashes on subpath directives */ while (!globalTmpDir.empty() && globalTmpDir.back() == '/') globalTmpDir.pop_back(); if (getEnv("_NIX_TEST_NO_SANDBOX") != "1") { Strings sandboxArgs; sandboxArgs.push_back("_GLOBAL_TMP_DIR"); sandboxArgs.push_back(globalTmpDir); if (allowLocalNetworking) { sandboxArgs.push_back("_ALLOW_LOCAL_NETWORKING"); sandboxArgs.push_back("1"); } char * sandbox_errbuf = nullptr; if (sandbox_init_with_parameters(sandboxProfile.c_str(), 0, stringsToCharPtrs(sandboxArgs).data(), &sandbox_errbuf)) { writeFull(STDERR_FILENO, fmt("failed to configure sandbox: %s\n", sandbox_errbuf ? sandbox_errbuf : "(null)")); _exit(1); } } #endif /* Indicate that we managed to set up the build environment. */ writeFull(STDERR_FILENO, std::string("\2\n")); sendException = false; /* Execute the program. This should not return. */ if (drv->isBuiltin()) { try { logger = makeJSONLogger(*logger); std::map<std::string, Path> outputs; for (auto & e : drv->outputs) outputs.insert_or_assign(e.first, worker.store.printStorePath(scratchOutputs.at(e.first))); if (drv->builder == "builtin:fetchurl") builtinFetchurl(*drv, outputs, netrcData, caFileData); else if (drv->builder == "builtin:buildenv") builtinBuildenv(*drv, outputs); else if (drv->builder == "builtin:unpack-channel") builtinUnpackChannel(*drv, outputs); else throw Error("unsupported builtin builder '%1%'", drv->builder.substr(8)); _exit(0); } catch (std::exception & e) { writeFull(STDERR_FILENO, e.what() + std::string("\n")); _exit(1); } } // Now builder is not builtin Strings args; args.push_back(std::string(baseNameOf(drv->builder))); for (auto & i : drv->args) args.push_back(rewriteStrings(i, inputRewrites)); #if __APPLE__ posix_spawnattr_t attrp; if (posix_spawnattr_init(&attrp)) throw SysError("failed to initialize builder"); if (posix_spawnattr_setflags(&attrp, POSIX_SPAWN_SETEXEC)) throw SysError("failed to initialize builder"); if (drv->platform == "aarch64-darwin") { // Unset kern.curproc_arch_affinity so we can escape Rosetta int affinity = 0; sysctlbyname("kern.curproc_arch_affinity", NULL, NULL, &affinity, sizeof(affinity)); cpu_type_t cpu = CPU_TYPE_ARM64; posix_spawnattr_setbinpref_np(&attrp, 1, &cpu, NULL); } else if (drv->platform == "x86_64-darwin") { cpu_type_t cpu = CPU_TYPE_X86_64; posix_spawnattr_setbinpref_np(&attrp, 1, &cpu, NULL); } posix_spawn(NULL, drv->builder.c_str(), NULL, &attrp, stringsToCharPtrs(args).data(), stringsToCharPtrs(envStrs).data()); #else execve(drv->builder.c_str(), stringsToCharPtrs(args).data(), stringsToCharPtrs(envStrs).data()); #endif throw SysError("executing '%1%'", drv->builder); } catch (...) { handleChildException(sendException); _exit(1); } } SingleDrvOutputs LocalDerivationGoal::registerOutputs() { /* When using a build hook, the build hook can register the output as valid (by doing `nix-store --import'). If so we don't have to do anything here. We can only early return when the outputs are known a priori. For floating content-addressed derivations this isn't the case. */ if (hook) return DerivationGoal::registerOutputs(); std::map<std::string, ValidPathInfo> infos; /* Set of inodes seen during calls to canonicalisePathMetaData() for this build's outputs. This needs to be shared between outputs to allow hard links between outputs. */ InodesSeen inodesSeen; Path checkSuffix = ".check"; std::exception_ptr delayedException; /* The paths that can be referenced are the input closures, the output paths, and any paths that have been built via recursive Nix calls. */ StorePathSet referenceablePaths; for (auto & p : inputPaths) referenceablePaths.insert(p); for (auto & i : scratchOutputs) referenceablePaths.insert(i.second); for (auto & p : addedPaths) referenceablePaths.insert(p); /* FIXME `needsHashRewrite` should probably be removed and we get to the real reason why we aren't using the chroot dir */ auto toRealPathChroot = [&](const Path & p) -> Path { return useChroot && !needsHashRewrite() ? chrootRootDir + p : worker.store.toRealPath(p); }; /* Check whether the output paths were created, and make all output paths read-only. Then get the references of each output (that we might need to register), so we can topologically sort them. For the ones that are most definitely already installed, we just store their final name so we can also use it in rewrites. */ StringSet outputsToSort; struct AlreadyRegistered { StorePath path; }; struct PerhapsNeedToRegister { StorePathSet refs; }; std::map<std::string, std::variant<AlreadyRegistered, PerhapsNeedToRegister>> outputReferencesIfUnregistered; std::map<std::string, struct stat> outputStats; for (auto & [outputName, _] : drv->outputs) { auto scratchOutput = get(scratchOutputs, outputName); if (!scratchOutput) throw BuildError( "builder for '%s' has no scratch output for '%s'", worker.store.printStorePath(drvPath), outputName); auto actualPath = toRealPathChroot(worker.store.printStorePath(*scratchOutput)); outputsToSort.insert(outputName); /* Updated wanted info to remove the outputs we definitely don't need to register */ auto initialOutput = get(initialOutputs, outputName); if (!initialOutput) throw BuildError( "builder for '%s' has no initial output for '%s'", worker.store.printStorePath(drvPath), outputName); auto & initialInfo = *initialOutput; /* Don't register if already valid, and not checking */ initialInfo.wanted = buildMode == bmCheck || !(initialInfo.known && initialInfo.known->isValid()); if (!initialInfo.wanted) { outputReferencesIfUnregistered.insert_or_assign( outputName, AlreadyRegistered { .path = initialInfo.known->path }); continue; } auto optSt = maybeLstat(actualPath.c_str()); if (!optSt) throw BuildError( "builder for '%s' failed to produce output path for output '%s' at '%s'", worker.store.printStorePath(drvPath), outputName, actualPath); struct stat & st = *optSt; #ifndef __CYGWIN__ /* Check that the output is not group or world writable, as that means that someone else can have interfered with the build. Also, the output should be owned by the build user. */ if ((!S_ISLNK(st.st_mode) && (st.st_mode & (S_IWGRP | S_IWOTH))) || (buildUser && st.st_uid != buildUser->getUID())) throw BuildError( "suspicious ownership or permission on '%s' for output '%s'; rejecting this build output", actualPath, outputName); #endif /* Canonicalise first. This ensures that the path we're rewriting doesn't contain a hard link to /etc/shadow or something like that. */ canonicalisePathMetaData( actualPath, buildUser ? std::optional(buildUser->getUIDRange()) : std::nullopt, inodesSeen); bool discardReferences = false; if (auto structuredAttrs = parsedDrv->getStructuredAttrs()) { if (auto udr = get(*structuredAttrs, "unsafeDiscardReferences")) { if (auto output = get(*udr, outputName)) { if (!output->is_boolean()) throw Error("attribute 'unsafeDiscardReferences.\"%s\"' of derivation '%s' must be a Boolean", outputName, drvPath.to_string()); discardReferences = output->get<bool>(); } } } StorePathSet references; if (discardReferences) debug("discarding references of output '%s'", outputName); else { debug("scanning for references for output '%s' in temp location '%s'", outputName, actualPath); /* Pass blank Sink as we are not ready to hash data at this stage. */ NullSink blank; references = scanForReferences(blank, actualPath, referenceablePaths); } outputReferencesIfUnregistered.insert_or_assign( outputName, PerhapsNeedToRegister { .refs = references }); outputStats.insert_or_assign(outputName, std::move(st)); } auto sortedOutputNames = topoSort(outputsToSort, {[&](const std::string & name) { auto orifu = get(outputReferencesIfUnregistered, name); if (!orifu) throw BuildError( "no output reference for '%s' in build of '%s'", name, worker.store.printStorePath(drvPath)); return std::visit(overloaded { /* Since we'll use the already installed versions of these, we can treat them as leaves and ignore any references they have. */ [&](const AlreadyRegistered &) { return StringSet {}; }, [&](const PerhapsNeedToRegister & refs) { StringSet referencedOutputs; /* FIXME build inverted map up front so no quadratic waste here */ for (auto & r : refs.refs) for (auto & [o, p] : scratchOutputs) if (r == p) referencedOutputs.insert(o); return referencedOutputs; }, }, *orifu); }}, {[&](const std::string & path, const std::string & parent) { // TODO with more -vvvv also show the temporary paths for manual inspection. return BuildError( "cycle detected in build of '%s' in the references of output '%s' from output '%s'", worker.store.printStorePath(drvPath), path, parent); }}); std::reverse(sortedOutputNames.begin(), sortedOutputNames.end()); OutputPathMap finalOutputs; for (auto & outputName : sortedOutputNames) { auto output = get(drv->outputs, outputName); auto scratchPath = get(scratchOutputs, outputName); assert(output && scratchPath); auto actualPath = toRealPathChroot(worker.store.printStorePath(*scratchPath)); auto finish = [&](StorePath finalStorePath) { /* Store the final path */ finalOutputs.insert_or_assign(outputName, finalStorePath); /* The rewrite rule will be used in downstream outputs that refer to use. This is why the topological sort is essential to do first before this for loop. */ if (*scratchPath != finalStorePath) outputRewrites[std::string { scratchPath->hashPart() }] = std::string { finalStorePath.hashPart() }; }; auto orifu = get(outputReferencesIfUnregistered, outputName); assert(orifu); std::optional<StorePathSet> referencesOpt = std::visit(overloaded { [&](const AlreadyRegistered & skippedFinalPath) -> std::optional<StorePathSet> { finish(skippedFinalPath.path); return std::nullopt; }, [&](const PerhapsNeedToRegister & r) -> std::optional<StorePathSet> { return r.refs; }, }, *orifu); if (!referencesOpt) continue; auto references = *referencesOpt; auto rewriteOutput = [&](const StringMap & rewrites) { /* Apply hash rewriting if necessary. */ if (!rewrites.empty()) { debug("rewriting hashes in '%1%'; cross fingers", actualPath); /* FIXME: Is this actually streaming? */ auto source = sinkToSource([&](Sink & nextSink) { RewritingSink rsink(rewrites, nextSink); dumpPath(actualPath, rsink); rsink.flush(); }); Path tmpPath = actualPath + ".tmp"; restorePath(tmpPath, *source); deletePath(actualPath); movePath(tmpPath, actualPath); /* FIXME: set proper permissions in restorePath() so we don't have to do another traversal. */ canonicalisePathMetaData(actualPath, {}, inodesSeen); } }; auto rewriteRefs = [&]() -> StoreReferences { /* In the CA case, we need the rewritten refs to calculate the final path, therefore we look for a *non-rewritten self-reference, and use a bool rather try to solve the computationally intractable fixed point. */ StoreReferences res { .self = false, }; for (auto & r : references) { auto name = r.name(); auto origHash = std::string { r.hashPart() }; if (r == *scratchPath) { res.self = true; } else if (auto outputRewrite = get(outputRewrites, origHash)) { std::string newRef = *outputRewrite; newRef += '-'; newRef += name; res.others.insert(StorePath { newRef }); } else { res.others.insert(r); } } return res; }; auto newInfoFromCA = [&](const DerivationOutput::CAFloating outputHash) -> ValidPathInfo { auto st = get(outputStats, outputName); if (!st) throw BuildError( "output path %1% without valid stats info", actualPath); if (outputHash.method.getFileIngestionMethod() == FileIngestionMethod::Flat) { /* The output path should be a regular file without execute permission. */ if (!S_ISREG(st->st_mode) || (st->st_mode & S_IXUSR) != 0) throw BuildError( "output path '%1%' should be a non-executable regular file " "since recursive hashing is not enabled (one of outputHashMode={flat,text} is true)", actualPath); } rewriteOutput(outputRewrites); /* FIXME optimize and deduplicate with addToStore */ std::string oldHashPart { scratchPath->hashPart() }; auto got = [&]{ auto fim = outputHash.method.getFileIngestionMethod(); switch (fim) { case FileIngestionMethod::Flat: case FileIngestionMethod::NixArchive: { HashModuloSink caSink { outputHash.hashAlgo, oldHashPart }; auto fim = outputHash.method.getFileIngestionMethod(); dumpPath( {getFSSourceAccessor(), CanonPath(actualPath)}, caSink, (FileSerialisationMethod) fim); return caSink.finish().first; } case FileIngestionMethod::Git: { return git::dumpHash( outputHash.hashAlgo, {getFSSourceAccessor(), CanonPath(tmpDir + "/tmp")}).hash; } } assert(false); }(); ValidPathInfo newInfo0 { worker.store, outputPathName(drv->name, outputName), ContentAddressWithReferences::fromParts( outputHash.method, std::move(got), rewriteRefs()), Hash::dummy, }; if (*scratchPath != newInfo0.path) { // If the path has some self-references, we need to rewrite // them. // (note that this doesn't invalidate the ca hash we calculated // above because it's computed *modulo the self-references*, so // it already takes this rewrite into account). rewriteOutput( StringMap{{oldHashPart, std::string(newInfo0.path.hashPart())}}); } { HashResult narHashAndSize = hashPath( {getFSSourceAccessor(), CanonPath(actualPath)}, FileSerialisationMethod::NixArchive, HashAlgorithm::SHA256); newInfo0.narHash = narHashAndSize.first; newInfo0.narSize = narHashAndSize.second; } assert(newInfo0.ca); return newInfo0; }; ValidPathInfo newInfo = std::visit(overloaded { [&](const DerivationOutput::InputAddressed & output) { /* input-addressed case */ auto requiredFinalPath = output.path; /* Preemptively add rewrite rule for final hash, as that is what the NAR hash will use rather than normalized-self references */ if (*scratchPath != requiredFinalPath) outputRewrites.insert_or_assign( std::string { scratchPath->hashPart() }, std::string { requiredFinalPath.hashPart() }); rewriteOutput(outputRewrites); HashResult narHashAndSize = hashPath( {getFSSourceAccessor(), CanonPath(actualPath)}, FileSerialisationMethod::NixArchive, HashAlgorithm::SHA256); ValidPathInfo newInfo0 { requiredFinalPath, narHashAndSize.first }; newInfo0.narSize = narHashAndSize.second; auto refs = rewriteRefs(); newInfo0.references = std::move(refs.others); if (refs.self) newInfo0.references.insert(newInfo0.path); return newInfo0; }, [&](const DerivationOutput::CAFixed & dof) { auto & wanted = dof.ca.hash; // Replace the output by a fresh copy of itself to make sure // that there's no stale file descriptor pointing to it Path tmpOutput = actualPath + ".tmp"; copyFile( std::filesystem::path(actualPath), std::filesystem::path(tmpOutput), true); std::filesystem::rename(tmpOutput, actualPath); auto newInfo0 = newInfoFromCA(DerivationOutput::CAFloating { .method = dof.ca.method, .hashAlgo = wanted.algo, }); /* Check wanted hash */ assert(newInfo0.ca); auto & got = newInfo0.ca->hash; if (wanted != got) { /* Throw an error after registering the path as valid. */ worker.hashMismatch = true; delayedException = std::make_exception_ptr( BuildError("hash mismatch in fixed-output derivation '%s':\n specified: %s\n got: %s", worker.store.printStorePath(drvPath), wanted.to_string(HashFormat::SRI, true), got.to_string(HashFormat::SRI, true))); } if (!newInfo0.references.empty()) delayedException = std::make_exception_ptr( BuildError("illegal path references in fixed-output derivation '%s'", worker.store.printStorePath(drvPath))); return newInfo0; }, [&](const DerivationOutput::CAFloating & dof) { return newInfoFromCA(dof); }, [&](const DerivationOutput::Deferred &) -> ValidPathInfo { // No derivation should reach that point without having been // rewritten first assert(false); }, [&](const DerivationOutput::Impure & doi) { return newInfoFromCA(DerivationOutput::CAFloating { .method = doi.method, .hashAlgo = doi.hashAlgo, }); }, }, output->raw); /* FIXME: set proper permissions in restorePath() so we don't have to do another traversal. */ canonicalisePathMetaData(actualPath, {}, inodesSeen); /* Calculate where we'll move the output files. In the checking case we will leave leave them where they are, for now, rather than move to their usual "final destination" */ auto finalDestPath = worker.store.printStorePath(newInfo.path); /* Lock final output path, if not already locked. This happens with floating CA derivations and hash-mismatching fixed-output derivations. */ PathLocks dynamicOutputLock; dynamicOutputLock.setDeletion(true); auto optFixedPath = output->path(worker.store, drv->name, outputName); if (!optFixedPath || worker.store.printStorePath(*optFixedPath) != finalDestPath) { assert(newInfo.ca); dynamicOutputLock.lockPaths({worker.store.toRealPath(finalDestPath)}); } /* Move files, if needed */ if (worker.store.toRealPath(finalDestPath) != actualPath) { if (buildMode == bmRepair) { /* Path already exists, need to replace it */ replaceValidPath(worker.store.toRealPath(finalDestPath), actualPath); actualPath = worker.store.toRealPath(finalDestPath); } else if (buildMode == bmCheck) { /* Path already exists, and we want to compare, so we leave out new path in place. */ } else if (worker.store.isValidPath(newInfo.path)) { /* Path already exists because CA path produced by something else. No moving needed. */ assert(newInfo.ca); } else { auto destPath = worker.store.toRealPath(finalDestPath); deletePath(destPath); movePath(actualPath, destPath); actualPath = destPath; } } auto & localStore = getLocalStore(); if (buildMode == bmCheck) { if (!worker.store.isValidPath(newInfo.path)) continue; ValidPathInfo oldInfo(*worker.store.queryPathInfo(newInfo.path)); if (newInfo.narHash != oldInfo.narHash) { worker.checkMismatch = true; if (settings.runDiffHook || settings.keepFailed) { auto dst = worker.store.toRealPath(finalDestPath + checkSuffix); deletePath(dst); movePath(actualPath, dst); handleDiffHook( buildUser ? buildUser->getUID() : getuid(), buildUser ? buildUser->getGID() : getgid(), finalDestPath, dst, worker.store.printStorePath(drvPath), tmpDir); throw NotDeterministic("derivation '%s' may not be deterministic: output '%s' differs from '%s'", worker.store.printStorePath(drvPath), worker.store.toRealPath(finalDestPath), dst); } else throw NotDeterministic("derivation '%s' may not be deterministic: output '%s' differs", worker.store.printStorePath(drvPath), worker.store.toRealPath(finalDestPath)); } /* Since we verified the build, it's now ultimately trusted. */ if (!oldInfo.ultimate) { oldInfo.ultimate = true; localStore.signPathInfo(oldInfo); localStore.registerValidPaths({{oldInfo.path, oldInfo}}); } continue; } /* For debugging, print out the referenced and unreferenced paths. */ for (auto & i : inputPaths) { if (references.count(i)) debug("referenced input: '%1%'", worker.store.printStorePath(i)); else debug("unreferenced input: '%1%'", worker.store.printStorePath(i)); } localStore.optimisePath(actualPath, NoRepair); // FIXME: combine with scanForReferences() worker.markContentsGood(newInfo.path); newInfo.deriver = drvPath; newInfo.ultimate = true; localStore.signPathInfo(newInfo); finish(newInfo.path); /* If it's a CA path, register it right away. This is necessary if it isn't statically known so that we can safely unlock the path before the next iteration */ if (newInfo.ca) localStore.registerValidPaths({{newInfo.path, newInfo}}); infos.emplace(outputName, std::move(newInfo)); } if (buildMode == bmCheck) { /* In case of fixed-output derivations, if there are mismatches on `--check` an error must be thrown as this is also a source for non-determinism. */ if (delayedException) std::rethrow_exception(delayedException); return assertPathValidity(); } /* Apply output checks. */ checkOutputs(infos); /* Register each output path as valid, and register the sets of paths referenced by each of them. If there are cycles in the outputs, this will fail. */ { auto & localStore = getLocalStore(); ValidPathInfos infos2; for (auto & [outputName, newInfo] : infos) { infos2.insert_or_assign(newInfo.path, newInfo); } localStore.registerValidPaths(infos2); } /* In case of a fixed-output derivation hash mismatch, throw an exception now that we have registered the output as valid. */ if (delayedException) std::rethrow_exception(delayedException); /* If we made it this far, we are sure the output matches the derivation (since the delayedException would be a fixed output CA mismatch). That means it's safe to link the derivation to the output hash. We must do that for floating CA derivations, which otherwise couldn't be cached, but it's fine to do in all cases. */ SingleDrvOutputs builtOutputs; for (auto & [outputName, newInfo] : infos) { auto oldinfo = get(initialOutputs, outputName); assert(oldinfo); auto thisRealisation = Realisation { .id = DrvOutput { oldinfo->outputHash, outputName }, .outPath = newInfo.path }; if (experimentalFeatureSettings.isEnabled(Xp::CaDerivations) && !drv->type().isImpure()) { signRealisation(thisRealisation); worker.store.registerDrvOutput(thisRealisation); } builtOutputs.emplace(outputName, thisRealisation); } return builtOutputs; } void LocalDerivationGoal::signRealisation(Realisation & realisation) { getLocalStore().signRealisation(realisation); } void LocalDerivationGoal::checkOutputs(const std::map<std::string, ValidPathInfo> & outputs) { std::map<Path, const ValidPathInfo &> outputsByPath; for (auto & output : outputs) outputsByPath.emplace(worker.store.printStorePath(output.second.path), output.second); for (auto & output : outputs) { auto & outputName = output.first; auto & info = output.second; struct Checks { bool ignoreSelfRefs = false; std::optional<uint64_t> maxSize, maxClosureSize; std::optional<Strings> allowedReferences, allowedRequisites, disallowedReferences, disallowedRequisites; }; /* Compute the closure and closure size of some output. This is slightly tricky because some of its references (namely other outputs) may not be valid yet. */ auto getClosure = [&](const StorePath & path) { uint64_t closureSize = 0; StorePathSet pathsDone; std::queue<StorePath> pathsLeft; pathsLeft.push(path); while (!pathsLeft.empty()) { auto path = pathsLeft.front(); pathsLeft.pop(); if (!pathsDone.insert(path).second) continue; auto i = outputsByPath.find(worker.store.printStorePath(path)); if (i != outputsByPath.end()) { closureSize += i->second.narSize; for (auto & ref : i->second.references) pathsLeft.push(ref); } else { auto info = worker.store.queryPathInfo(path); closureSize += info->narSize; for (auto & ref : info->references) pathsLeft.push(ref); } } return std::make_pair(std::move(pathsDone), closureSize); }; auto applyChecks = [&](const Checks & checks) { if (checks.maxSize && info.narSize > *checks.maxSize) throw BuildError("path '%s' is too large at %d bytes; limit is %d bytes", worker.store.printStorePath(info.path), info.narSize, *checks.maxSize); if (checks.maxClosureSize) { uint64_t closureSize = getClosure(info.path).second; if (closureSize > *checks.maxClosureSize) throw BuildError("closure of path '%s' is too large at %d bytes; limit is %d bytes", worker.store.printStorePath(info.path), closureSize, *checks.maxClosureSize); } auto checkRefs = [&](const std::optional<Strings> & value, bool allowed, bool recursive) { if (!value) return; /* Parse a list of reference specifiers. Each element must either be a store path, or the symbolic name of the output of the derivation (such as `out'). */ StorePathSet spec; for (auto & i : *value) { if (worker.store.isStorePath(i)) spec.insert(worker.store.parseStorePath(i)); else if (auto output = get(outputs, i)) spec.insert(output->path); else throw BuildError("derivation contains an illegal reference specifier '%s'", i); } auto used = recursive ? getClosure(info.path).first : info.references; if (recursive && checks.ignoreSelfRefs) used.erase(info.path); StorePathSet badPaths; for (auto & i : used) if (allowed) { if (!spec.count(i)) badPaths.insert(i); } else { if (spec.count(i)) badPaths.insert(i); } if (!badPaths.empty()) { std::string badPathsStr; for (auto & i : badPaths) { badPathsStr += "\n "; badPathsStr += worker.store.printStorePath(i); } throw BuildError("output '%s' is not allowed to refer to the following paths:%s", worker.store.printStorePath(info.path), badPathsStr); } }; checkRefs(checks.allowedReferences, true, false); checkRefs(checks.allowedRequisites, true, true); checkRefs(checks.disallowedReferences, false, false); checkRefs(checks.disallowedRequisites, false, true); }; if (auto structuredAttrs = parsedDrv->getStructuredAttrs()) { if (get(*structuredAttrs, "allowedReferences")){ warn("'structuredAttrs' disables the effect of the top-level attribute 'allowedReferences'; use 'outputChecks' instead"); } if (get(*structuredAttrs, "allowedRequisites")){ warn("'structuredAttrs' disables the effect of the top-level attribute 'allowedRequisites'; use 'outputChecks' instead"); } if (get(*structuredAttrs, "disallowedRequisites")){ warn("'structuredAttrs' disables the effect of the top-level attribute 'disallowedRequisites'; use 'outputChecks' instead"); } if (get(*structuredAttrs, "disallowedReferences")){ warn("'structuredAttrs' disables the effect of the top-level attribute 'disallowedReferences'; use 'outputChecks' instead"); } if (get(*structuredAttrs, "maxSize")){ warn("'structuredAttrs' disables the effect of the top-level attribute 'maxSize'; use 'outputChecks' instead"); } if (get(*structuredAttrs, "maxClosureSize")){ warn("'structuredAttrs' disables the effect of the top-level attribute 'maxClosureSize'; use 'outputChecks' instead"); } if (auto outputChecks = get(*structuredAttrs, "outputChecks")) { if (auto output = get(*outputChecks, outputName)) { Checks checks; if (auto maxSize = get(*output, "maxSize")) checks.maxSize = maxSize->get<uint64_t>(); if (auto maxClosureSize = get(*output, "maxClosureSize")) checks.maxClosureSize = maxClosureSize->get<uint64_t>(); auto get_ = [&](const std::string & name) -> std::optional<Strings> { if (auto i = get(*output, name)) { Strings res; for (auto j = i->begin(); j != i->end(); ++j) { if (!j->is_string()) throw Error("attribute '%s' of derivation '%s' must be a list of strings", name, worker.store.printStorePath(drvPath)); res.push_back(j->get<std::string>()); } checks.disallowedRequisites = res; return res; } return {}; }; checks.allowedReferences = get_("allowedReferences"); checks.allowedRequisites = get_("allowedRequisites"); checks.disallowedReferences = get_("disallowedReferences"); checks.disallowedRequisites = get_("disallowedRequisites"); applyChecks(checks); } } } else { // legacy non-structured-attributes case Checks checks; checks.ignoreSelfRefs = true; checks.allowedReferences = parsedDrv->getStringsAttr("allowedReferences"); checks.allowedRequisites = parsedDrv->getStringsAttr("allowedRequisites"); checks.disallowedReferences = parsedDrv->getStringsAttr("disallowedReferences"); checks.disallowedRequisites = parsedDrv->getStringsAttr("disallowedRequisites"); applyChecks(checks); } } } void LocalDerivationGoal::deleteTmpDir(bool force) { if (topTmpDir != "") { /* Don't keep temporary directories for builtins because they might have privileged stuff (like a copy of netrc). */ if (settings.keepFailed && !force && !drv->isBuiltin()) { printError("note: keeping build directory '%s'", tmpDir); chmod(topTmpDir.c_str(), 0755); chmod(tmpDir.c_str(), 0755); } else deletePath(topTmpDir); topTmpDir = ""; tmpDir = ""; } } bool LocalDerivationGoal::isReadDesc(int fd) { return (hook && DerivationGoal::isReadDesc(fd)) || (!hook && fd == builderOut.get()); } StorePath LocalDerivationGoal::makeFallbackPath(OutputNameView outputName) { // This is a bogus path type, constructed this way to ensure that it doesn't collide with any other store path // See doc/manual/source/protocols/store-path.md for details // TODO: We may want to separate the responsibilities of constructing the path fingerprint and of actually doing the hashing auto pathType = "rewrite:" + std::string(drvPath.to_string()) + ":name:" + std::string(outputName); return worker.store.makeStorePath( pathType, // pass an all-zeroes hash Hash(HashAlgorithm::SHA256), outputPathName(drv->name, outputName)); } StorePath LocalDerivationGoal::makeFallbackPath(const StorePath & path) { // This is a bogus path type, constructed this way to ensure that it doesn't collide with any other store path // See doc/manual/source/protocols/store-path.md for details auto pathType = "rewrite:" + std::string(drvPath.to_string()) + ":" + std::string(path.to_string()); return worker.store.makeStorePath( pathType, // pass an all-zeroes hash Hash(HashAlgorithm::SHA256), path.name()); } }
120,485
C++
.cc
2,572
35.595645
157
0.588964
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,850
child.cc
NixOS_nix/src/libstore/unix/build/child.cc
#include "child.hh" #include "current-process.hh" #include "logging.hh" #include <fcntl.h> #include <unistd.h> namespace nix { void commonChildInit() { logger = makeSimpleLogger(); const static std::string pathNullDevice = "/dev/null"; restoreProcessContext(false); /* Put the child in a separate session (and thus a separate process group) so that it has no controlling terminal (meaning that e.g. ssh cannot open /dev/tty) and it doesn't receive terminal signals. */ if (setsid() == -1) throw SysError("creating a new session"); /* Dup stderr to stdout. */ if (dup2(STDERR_FILENO, STDOUT_FILENO) == -1) throw SysError("cannot dup stderr into stdout"); /* Reroute stdin to /dev/null. */ int fdDevNull = open(pathNullDevice.c_str(), O_RDWR); if (fdDevNull == -1) throw SysError("cannot open '%1%'", pathNullDevice); if (dup2(fdDevNull, STDIN_FILENO) == -1) throw SysError("cannot dup null device into stdin"); close(fdDevNull); } }
1,041
C++
.cc
29
31.137931
69
0.670319
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,851
hook-instance.cc
NixOS_nix/src/libstore/unix/build/hook-instance.cc
#include "globals.hh" #include "config-global.hh" #include "hook-instance.hh" #include "file-system.hh" #include "child.hh" #include "strings.hh" #include "executable-path.hh" namespace nix { HookInstance::HookInstance() { debug("starting build hook '%s'", concatStringsSep(" ", settings.buildHook.get())); auto buildHookArgs = settings.buildHook.get(); if (buildHookArgs.empty()) throw Error("'build-hook' setting is empty"); std::filesystem::path buildHook = buildHookArgs.front(); buildHookArgs.pop_front(); try { buildHook = ExecutablePath::load().findPath(buildHook); } catch (ExecutableLookupError & e) { e.addTrace(nullptr, "while resolving the 'build-hook' setting'"); throw; } Strings args; args.push_back(buildHook.filename().string()); for (auto & arg : buildHookArgs) args.push_back(arg); args.push_back(std::to_string(verbosity)); /* Create a pipe to get the output of the child. */ fromHook.create(); /* Create the communication pipes. */ toHook.create(); /* Create a pipe to get the output of the builder. */ builderOut.create(); /* Fork the hook. */ pid = startProcess([&]() { if (dup2(fromHook.writeSide.get(), STDERR_FILENO) == -1) throw SysError("cannot pipe standard error into log file"); commonChildInit(); if (chdir("/") == -1) throw SysError("changing into /"); /* Dup the communication pipes. */ if (dup2(toHook.readSide.get(), STDIN_FILENO) == -1) throw SysError("dupping to-hook read side"); /* Use fd 4 for the builder's stdout/stderr. */ if (dup2(builderOut.writeSide.get(), 4) == -1) throw SysError("dupping builder's stdout/stderr"); /* Hack: pass the read side of that fd to allow build-remote to read SSH error messages. */ if (dup2(builderOut.readSide.get(), 5) == -1) throw SysError("dupping builder's stdout/stderr"); execv(buildHook.native().c_str(), stringsToCharPtrs(args).data()); throw SysError("executing '%s'", buildHook); }); pid.setSeparatePG(true); fromHook.writeSide = -1; toHook.readSide = -1; sink = FdSink(toHook.writeSide.get()); std::map<std::string, Config::SettingInfo> settings; globalConfig.getSettings(settings); for (auto & setting : settings) sink << 1 << setting.first << setting.second.value; sink << 0; } HookInstance::~HookInstance() { try { toHook.writeSide = -1; if (pid != -1) pid.kill(); } catch (...) { ignoreExceptionInDestructor(); } } }
2,681
C++
.cc
72
31.055556
87
0.634533
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,852
pathlocks.cc
NixOS_nix/src/libstore/windows/pathlocks.cc
#include "logging.hh" #include "pathlocks.hh" #include "signals.hh" #include "util.hh" #include <errhandlingapi.h> #include <fileapi.h> #include <windows.h> #include "windows-error.hh" namespace nix { using namespace nix::windows; void deleteLockFile(const Path & path, Descriptor desc) { int exit = DeleteFileA(path.c_str()); if (exit == 0) warn("%s: &s", path, std::to_string(GetLastError())); } void PathLocks::unlock() { for (auto & i : fds) { if (deletePaths) deleteLockFile(i.second, i.first); if (CloseHandle(i.first) == -1) printError("error (ignored): cannot close lock file on '%1%'", i.second); debug("lock released on '%1%'", i.second); } fds.clear(); } AutoCloseFD openLockFile(const Path & path, bool create) { AutoCloseFD desc = CreateFileA( path.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, create ? OPEN_ALWAYS : OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_POSIX_SEMANTICS, NULL); if (desc.get() == INVALID_HANDLE_VALUE) warn("%s: %s", path, std::to_string(GetLastError())); return desc; } bool lockFile(Descriptor desc, LockType lockType, bool wait) { switch (lockType) { case ltNone: { OVERLAPPED ov = {0}; if (!UnlockFileEx(desc, 0, 2, 0, &ov)) { WinError winError("Failed to unlock file desc %s", desc); throw winError; } return true; } case ltRead: { OVERLAPPED ov = {0}; if (!LockFileEx(desc, wait ? 0 : LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, &ov)) { WinError winError("Failed to lock file desc %s", desc); if (winError.lastError == ERROR_LOCK_VIOLATION) return false; throw winError; } ov.Offset = 1; if (!UnlockFileEx(desc, 0, 1, 0, &ov)) { WinError winError("Failed to unlock file desc %s", desc); if (winError.lastError != ERROR_NOT_LOCKED) throw winError; } return true; } case ltWrite: { OVERLAPPED ov = {0}; ov.Offset = 1; if (!LockFileEx(desc, LOCKFILE_EXCLUSIVE_LOCK | (wait ? 0 : LOCKFILE_FAIL_IMMEDIATELY), 0, 1, 0, &ov)) { WinError winError("Failed to lock file desc %s", desc); if (winError.lastError == ERROR_LOCK_VIOLATION) return false; throw winError; } ov.Offset = 0; if (!UnlockFileEx(desc, 0, 1, 0, &ov)) { WinError winError("Failed to unlock file desc %s", desc); if (winError.lastError != ERROR_NOT_LOCKED) throw winError; } return true; } default: assert(false); } } bool PathLocks::lockPaths(const PathSet & paths, const std::string & waitMsg, bool wait) { assert(fds.empty()); for (auto & path : paths) { checkInterrupt(); Path lockPath = path + ".lock"; debug("locking path '%1%'", path); AutoCloseFD fd; while (1) { fd = openLockFile(lockPath, true); if (!lockFile(fd.get(), ltWrite, false)) { if (wait) { if (waitMsg != "") printError(waitMsg); lockFile(fd.get(), ltWrite, true); } else { unlock(); return false; } } debug("lock aquired on '%1%'", lockPath); struct _stat st; if (_fstat(fromDescriptorReadOnly(fd.get()), &st) == -1) throw SysError("statting lock file '%1%'", lockPath); if (st.st_size != 0) debug("open lock file '%1%' has become stale", lockPath); else break; } fds.push_back(FDPair(fd.release(), lockPath)); } return true; } FdLock::FdLock(Descriptor desc, LockType lockType, bool wait, std::string_view waitMsg) : desc(desc) { if (wait) { if (!lockFile(desc, lockType, false)) { printInfo("%s", waitMsg); acquired = lockFile(desc, lockType, true); } } else acquired = lockFile(desc, lockType, false); } }
4,320
C++
.cc
134
23.731343
112
0.549472
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,853
substitution-goal.cc
NixOS_nix/src/libstore/build/substitution-goal.cc
#include "worker.hh" #include "substitution-goal.hh" #include "nar-info.hh" #include "finally.hh" #include "signals.hh" #include <coroutine> namespace nix { PathSubstitutionGoal::PathSubstitutionGoal(const StorePath & storePath, Worker & worker, RepairFlag repair, std::optional<ContentAddress> ca) : Goal(worker, DerivedPath::Opaque { storePath }) , storePath(storePath) , repair(repair) , ca(ca) { name = fmt("substitution of '%s'", worker.store.printStorePath(this->storePath)); trace("created"); maintainExpectedSubstitutions = std::make_unique<MaintainCount<uint64_t>>(worker.expectedSubstitutions); } PathSubstitutionGoal::~PathSubstitutionGoal() { cleanup(); } Goal::Done PathSubstitutionGoal::done( ExitCode result, BuildResult::Status status, std::optional<std::string> errorMsg) { buildResult.status = status; if (errorMsg) { debug(*errorMsg); buildResult.errorMsg = *errorMsg; } return amDone(result); } Goal::Co PathSubstitutionGoal::init() { trace("init"); worker.store.addTempRoot(storePath); /* If the path already exists we're done. */ if (!repair && worker.store.isValidPath(storePath)) { co_return done(ecSuccess, BuildResult::AlreadyValid); } if (settings.readOnlyMode) throw Error("cannot substitute path '%s' - no write access to the Nix store", worker.store.printStorePath(storePath)); auto subs = settings.useSubstitutes ? getDefaultSubstituters() : std::list<ref<Store>>(); bool substituterFailed = false; for (auto sub : subs) { trace("trying next substituter"); cleanup(); /* The path the substituter refers to the path as. This will be * different when the stores have different names. */ std::optional<StorePath> subPath; /* Path info returned by the substituter's query info operation. */ std::shared_ptr<const ValidPathInfo> info; if (ca) { subPath = sub->makeFixedOutputPathFromCA( std::string { storePath.name() }, ContentAddressWithReferences::withoutRefs(*ca)); if (sub->storeDir == worker.store.storeDir) assert(subPath == storePath); } else if (sub->storeDir != worker.store.storeDir) { continue; } try { // FIXME: make async info = sub->queryPathInfo(subPath ? *subPath : storePath); } catch (InvalidPath &) { continue; } catch (SubstituterDisabled & e) { if (settings.tryFallback) continue; else throw e; } catch (Error & e) { if (settings.tryFallback) { logError(e.info()); continue; } else throw e; } if (info->path != storePath) { if (info->isContentAddressed(*sub) && info->references.empty()) { auto info2 = std::make_shared<ValidPathInfo>(*info); info2->path = storePath; info = info2; } else { printError("asked '%s' for '%s' but got '%s'", sub->getUri(), worker.store.printStorePath(storePath), sub->printStorePath(info->path)); continue; } } /* Update the total expected download size. */ auto narInfo = std::dynamic_pointer_cast<const NarInfo>(info); maintainExpectedNar = std::make_unique<MaintainCount<uint64_t>>(worker.expectedNarSize, info->narSize); maintainExpectedDownload = narInfo && narInfo->fileSize ? std::make_unique<MaintainCount<uint64_t>>(worker.expectedDownloadSize, narInfo->fileSize) : nullptr; worker.updateProgress(); /* Bail out early if this substituter lacks a valid signature. LocalStore::addToStore() also checks for this, but only after we've downloaded the path. */ if (!sub->isTrusted && worker.store.pathInfoIsUntrusted(*info)) { warn("ignoring substitute for '%s' from '%s', as it's not signed by any of the keys in 'trusted-public-keys'", worker.store.printStorePath(storePath), sub->getUri()); continue; } /* To maintain the closure invariant, we first have to realise the paths referenced by this one. */ for (auto & i : info->references) if (i != storePath) /* ignore self-references */ addWaitee(worker.makePathSubstitutionGoal(i)); if (!waitees.empty()) co_await Suspend{}; // FIXME: consider returning boolean instead of passing in reference bool out = false; // is mutated by tryToRun co_await tryToRun(subPath ? *subPath : storePath, sub, info, out); substituterFailed = substituterFailed || out; } /* None left. Terminate this goal and let someone else deal with it. */ if (substituterFailed) { worker.failedSubstitutions++; worker.updateProgress(); } /* Hack: don't indicate failure if there were no substituters. In that case the calling derivation should just do a build. */ co_return done( substituterFailed ? ecFailed : ecNoSubstituters, BuildResult::NoSubstituters, fmt("path '%s' is required, but there is no substituter that can build it", worker.store.printStorePath(storePath))); } Goal::Co PathSubstitutionGoal::tryToRun(StorePath subPath, nix::ref<Store> sub, std::shared_ptr<const ValidPathInfo> info, bool & substituterFailed) { trace("all references realised"); if (nrFailed > 0) { co_return done( nrNoSubstituters > 0 || nrIncompleteClosure > 0 ? ecIncompleteClosure : ecFailed, BuildResult::DependencyFailed, fmt("some references of path '%s' could not be realised", worker.store.printStorePath(storePath))); } for (auto & i : info->references) if (i != storePath) /* ignore self-references */ assert(worker.store.isValidPath(i)); worker.wakeUp(shared_from_this()); co_await Suspend{}; trace("trying to run"); /* Make sure that we are allowed to start a substitution. Note that even if maxSubstitutionJobs == 0, we still allow a substituter to run. This prevents infinite waiting. */ while (worker.getNrSubstitutions() >= std::max(1U, (unsigned int) settings.maxSubstitutionJobs)) { worker.waitForBuildSlot(shared_from_this()); co_await Suspend{}; } auto maintainRunningSubstitutions = std::make_unique<MaintainCount<uint64_t>>(worker.runningSubstitutions); worker.updateProgress(); #ifndef _WIN32 outPipe.create(); #else outPipe.createAsyncPipe(worker.ioport.get()); #endif auto promise = std::promise<void>(); thr = std::thread([this, &promise, &subPath, &sub]() { try { ReceiveInterrupts receiveInterrupts; /* Wake up the worker loop when we're done. */ Finally updateStats([this]() { outPipe.writeSide.close(); }); Activity act(*logger, actSubstitute, Logger::Fields{worker.store.printStorePath(storePath), sub->getUri()}); PushActivity pact(act.id); copyStorePath(*sub, worker.store, subPath, repair, sub->isTrusted ? NoCheckSigs : CheckSigs); promise.set_value(); } catch (...) { promise.set_exception(std::current_exception()); } }); worker.childStarted(shared_from_this(), { #ifndef _WIN32 outPipe.readSide.get() #else &outPipe #endif }, true, false); co_await Suspend{}; trace("substitute finished"); thr.join(); worker.childTerminated(this); try { promise.get_future().get(); } catch (std::exception & e) { printError(e.what()); /* Cause the parent build to fail unless --fallback is given, or the substitute has disappeared. The latter case behaves the same as the substitute never having existed in the first place. */ try { throw; } catch (SubstituteGone &) { } catch (...) { substituterFailed = true; } co_return Return{}; } worker.markContentsGood(storePath); printMsg(lvlChatty, "substitution of path '%s' succeeded", worker.store.printStorePath(storePath)); maintainRunningSubstitutions.reset(); maintainExpectedSubstitutions.reset(); worker.doneSubstitutions++; if (maintainExpectedDownload) { auto fileSize = maintainExpectedDownload->delta; maintainExpectedDownload.reset(); worker.doneDownloadSize += fileSize; } assert(maintainExpectedNar); worker.doneNarSize += maintainExpectedNar->delta; maintainExpectedNar.reset(); worker.updateProgress(); co_return done(ecSuccess, BuildResult::Substituted); } void PathSubstitutionGoal::handleEOF(Descriptor fd) { worker.wakeUp(shared_from_this()); } void PathSubstitutionGoal::cleanup() { try { if (thr.joinable()) { // FIXME: signal worker thread to quit. thr.join(); worker.childTerminated(this); } outPipe.close(); } catch (...) { ignoreExceptionInDestructor(); } } }
9,388
C++
.cc
234
32.08547
148
0.637354
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
10,854
derivation-goal.cc
NixOS_nix/src/libstore/build/derivation-goal.cc
#include "derivation-goal.hh" #ifndef _WIN32 // TODO enable build hook on Windows # include "hook-instance.hh" #endif #include "processes.hh" #include "config-global.hh" #include "worker.hh" #include "builtins.hh" #include "builtins/buildenv.hh" #include "references.hh" #include "finally.hh" #include "util.hh" #include "archive.hh" #include "compression.hh" #include "common-protocol.hh" #include "common-protocol-impl.hh" #include "topo-sort.hh" #include "callback.hh" #include "local-store.hh" // TODO remove, along with remaining downcasts #include <regex> #include <queue> #include <fstream> #include <sys/types.h> #include <fcntl.h> #include <unistd.h> #ifndef _WIN32 // TODO abstract over proc exit status # include <sys/wait.h> #endif #include <nlohmann/json.hpp> #include "strings.hh" namespace nix { Goal::Co DerivationGoal::init() { if (useDerivation) { co_return getDerivation(); } else { co_return haveDerivation(); } } DerivationGoal::DerivationGoal(const StorePath & drvPath, const OutputsSpec & wantedOutputs, Worker & worker, BuildMode buildMode) : Goal(worker, DerivedPath::Built { .drvPath = makeConstantStorePathRef(drvPath), .outputs = wantedOutputs }) , useDerivation(true) , drvPath(drvPath) , wantedOutputs(wantedOutputs) , buildMode(buildMode) { name = fmt( "building of '%s' from .drv file", DerivedPath::Built { makeConstantStorePathRef(drvPath), wantedOutputs }.to_string(worker.store)); trace("created"); mcExpectedBuilds = std::make_unique<MaintainCount<uint64_t>>(worker.expectedBuilds); worker.updateProgress(); } DerivationGoal::DerivationGoal(const StorePath & drvPath, const BasicDerivation & drv, const OutputsSpec & wantedOutputs, Worker & worker, BuildMode buildMode) : Goal(worker, DerivedPath::Built { .drvPath = makeConstantStorePathRef(drvPath), .outputs = wantedOutputs }) , useDerivation(false) , drvPath(drvPath) , wantedOutputs(wantedOutputs) , buildMode(buildMode) { this->drv = std::make_unique<Derivation>(drv); name = fmt( "building of '%s' from in-memory derivation", DerivedPath::Built { makeConstantStorePathRef(drvPath), drv.outputNames() }.to_string(worker.store)); trace("created"); mcExpectedBuilds = std::make_unique<MaintainCount<uint64_t>>(worker.expectedBuilds); worker.updateProgress(); /* Prevent the .chroot directory from being garbage-collected. (See isActiveTempFile() in gc.cc.) */ worker.store.addTempRoot(this->drvPath); } DerivationGoal::~DerivationGoal() { /* Careful: we should never ever throw an exception from a destructor. */ try { closeLogFile(); } catch (...) { ignoreExceptionInDestructor(); } } std::string DerivationGoal::key() { /* Ensure that derivations get built in order of their name, i.e. a derivation named "aardvark" always comes before "baboon". And substitution goals always happen before derivation goals (due to "b$"). */ return "b$" + std::string(drvPath.name()) + "$" + worker.store.printStorePath(drvPath); } void DerivationGoal::killChild() { #ifndef _WIN32 // TODO enable build hook on Windows hook.reset(); #endif } void DerivationGoal::timedOut(Error && ex) { killChild(); // We're not inside a coroutine, hence we can't use co_return here. // Thus we ignore the return value. [[maybe_unused]] Done _ = done(BuildResult::TimedOut, {}, std::move(ex)); } void DerivationGoal::addWantedOutputs(const OutputsSpec & outputs) { auto newWanted = wantedOutputs.union_(outputs); switch (needRestart) { case NeedRestartForMoreOutputs::OutputsUnmodifedDontNeed: if (!newWanted.isSubsetOf(wantedOutputs)) needRestart = NeedRestartForMoreOutputs::OutputsAddedDoNeed; break; case NeedRestartForMoreOutputs::OutputsAddedDoNeed: /* No need to check whether we added more outputs, because a restart is already queued up. */ break; case NeedRestartForMoreOutputs::BuildInProgressWillNotNeed: /* We are already building all outputs, so it doesn't matter if we now want more. */ break; }; wantedOutputs = newWanted; } Goal::Co DerivationGoal::getDerivation() { trace("init"); /* The first thing to do is to make sure that the derivation exists. If it doesn't, it may be created through a substitute. */ if (buildMode == bmNormal && worker.evalStore.isValidPath(drvPath)) { co_return loadDerivation(); } addWaitee(upcast_goal(worker.makePathSubstitutionGoal(drvPath))); co_await Suspend{}; co_return loadDerivation(); } Goal::Co DerivationGoal::loadDerivation() { trace("loading derivation"); if (nrFailed != 0) { co_return done(BuildResult::MiscFailure, {}, Error("cannot build missing derivation '%s'", worker.store.printStorePath(drvPath))); } /* `drvPath' should already be a root, but let's be on the safe side: if the user forgot to make it a root, we wouldn't want things being garbage collected while we're busy. */ worker.evalStore.addTempRoot(drvPath); /* Get the derivation. It is probably in the eval store, but it might be inthe main store: - Resolved derivation are resolved against main store realisations, and so must be stored there. - Dynamic derivations are built, and so are found in the main store. */ for (auto * drvStore : { &worker.evalStore, &worker.store }) { if (drvStore->isValidPath(drvPath)) { drv = std::make_unique<Derivation>(drvStore->readDerivation(drvPath)); break; } } assert(drv); co_return haveDerivation(); } Goal::Co DerivationGoal::haveDerivation() { trace("have derivation"); parsedDrv = std::make_unique<ParsedDerivation>(drvPath, *drv); if (!drv->type().hasKnownOutputPaths()) experimentalFeatureSettings.require(Xp::CaDerivations); if (drv->type().isImpure()) { experimentalFeatureSettings.require(Xp::ImpureDerivations); for (auto & [outputName, output] : drv->outputs) { auto randomPath = StorePath::random(outputPathName(drv->name, outputName)); assert(!worker.store.isValidPath(randomPath)); initialOutputs.insert({ outputName, InitialOutput { .wanted = true, .outputHash = impureOutputHash, .known = InitialOutputStatus { .path = randomPath, .status = PathStatus::Absent } } }); } co_return gaveUpOnSubstitution(); } for (auto & i : drv->outputsAndOptPaths(worker.store)) if (i.second.second) worker.store.addTempRoot(*i.second.second); auto outputHashes = staticOutputHashes(worker.evalStore, *drv); for (auto & [outputName, outputHash] : outputHashes) initialOutputs.insert({ outputName, InitialOutput { .wanted = true, // Will be refined later .outputHash = outputHash } }); /* Check what outputs paths are not already valid. */ auto [allValid, validOutputs] = checkPathValidity(); /* If they are all valid, then we're done. */ if (allValid && buildMode == bmNormal) { co_return done(BuildResult::AlreadyValid, std::move(validOutputs)); } /* We are first going to try to create the invalid output paths through substitutes. If that doesn't work, we'll build them. */ if (settings.useSubstitutes && parsedDrv->substitutesAllowed()) for (auto & [outputName, status] : initialOutputs) { if (!status.wanted) continue; if (!status.known) addWaitee( upcast_goal( worker.makeDrvOutputSubstitutionGoal( DrvOutput{status.outputHash, outputName}, buildMode == bmRepair ? Repair : NoRepair ) ) ); else { auto * cap = getDerivationCA(*drv); addWaitee(upcast_goal(worker.makePathSubstitutionGoal( status.known->path, buildMode == bmRepair ? Repair : NoRepair, cap ? std::optional { *cap } : std::nullopt))); } } if (!waitees.empty()) co_await Suspend{}; /* to prevent hang (no wake-up event) */ co_return outputsSubstitutionTried(); } Goal::Co DerivationGoal::outputsSubstitutionTried() { trace("all outputs substituted (maybe)"); assert(!drv->type().isImpure()); if (nrFailed > 0 && nrFailed > nrNoSubstituters + nrIncompleteClosure && !settings.tryFallback) { co_return done(BuildResult::TransientFailure, {}, Error("some substitutes for the outputs of derivation '%s' failed (usually happens due to networking issues); try '--fallback' to build derivation from source ", worker.store.printStorePath(drvPath))); } /* If the substitutes form an incomplete closure, then we should build the dependencies of this derivation, but after that, we can still use the substitutes for this derivation itself. If the nrIncompleteClosure != nrFailed, we have another issue as well. In particular, it may be the case that the hole in the closure is an output of the current derivation, which causes a loop if retried. */ { bool substitutionFailed = nrIncompleteClosure > 0 && nrIncompleteClosure == nrFailed; switch (retrySubstitution) { case RetrySubstitution::NoNeed: if (substitutionFailed) retrySubstitution = RetrySubstitution::YesNeed; break; case RetrySubstitution::YesNeed: // Should not be able to reach this state from here. assert(false); break; case RetrySubstitution::AlreadyRetried: debug("substitution failed again, but we already retried once. Not retrying again."); break; } } nrFailed = nrNoSubstituters = nrIncompleteClosure = 0; if (needRestart == NeedRestartForMoreOutputs::OutputsAddedDoNeed) { needRestart = NeedRestartForMoreOutputs::OutputsUnmodifedDontNeed; co_return haveDerivation(); } auto [allValid, validOutputs] = checkPathValidity(); if (buildMode == bmNormal && allValid) { co_return done(BuildResult::Substituted, std::move(validOutputs)); } if (buildMode == bmRepair && allValid) { co_return repairClosure(); } if (buildMode == bmCheck && !allValid) throw Error("some outputs of '%s' are not valid, so checking is not possible", worker.store.printStorePath(drvPath)); /* Nothing to wait for; tail call */ co_return gaveUpOnSubstitution(); } /* At least one of the output paths could not be produced using a substitute. So we have to build instead. */ Goal::Co DerivationGoal::gaveUpOnSubstitution() { /* At this point we are building all outputs, so if more are wanted there is no need to restart. */ needRestart = NeedRestartForMoreOutputs::BuildInProgressWillNotNeed; /* The inputs must be built before we can build this goal. */ inputDrvOutputs.clear(); if (useDerivation) { std::function<void(ref<SingleDerivedPath>, const DerivedPathMap<StringSet>::ChildNode &)> addWaiteeDerivedPath; addWaiteeDerivedPath = [&](ref<SingleDerivedPath> inputDrv, const DerivedPathMap<StringSet>::ChildNode & inputNode) { if (!inputNode.value.empty()) addWaitee(worker.makeGoal( DerivedPath::Built { .drvPath = inputDrv, .outputs = inputNode.value, }, buildMode == bmRepair ? bmRepair : bmNormal)); for (const auto & [outputName, childNode] : inputNode.childMap) addWaiteeDerivedPath( make_ref<SingleDerivedPath>(SingleDerivedPath::Built { inputDrv, outputName }), childNode); }; for (const auto & [inputDrvPath, inputNode] : dynamic_cast<Derivation *>(drv.get())->inputDrvs.map) { /* Ensure that pure, non-fixed-output derivations don't depend on impure derivations. */ if (experimentalFeatureSettings.isEnabled(Xp::ImpureDerivations) && !drv->type().isImpure() && !drv->type().isFixed()) { auto inputDrv = worker.evalStore.readDerivation(inputDrvPath); if (inputDrv.type().isImpure()) throw Error("pure derivation '%s' depends on impure derivation '%s'", worker.store.printStorePath(drvPath), worker.store.printStorePath(inputDrvPath)); } addWaiteeDerivedPath(makeConstantStorePathRef(inputDrvPath), inputNode); } } /* Copy the input sources from the eval store to the build store. Note that some inputs might not be in the eval store because they are (resolved) derivation outputs in a resolved derivation. */ if (&worker.evalStore != &worker.store) { RealisedPath::Set inputSrcs; for (auto & i : drv->inputSrcs) if (worker.evalStore.isValidPath(i)) inputSrcs.insert(i); copyClosure(worker.evalStore, worker.store, inputSrcs); } for (auto & i : drv->inputSrcs) { if (worker.store.isValidPath(i)) continue; if (!settings.useSubstitutes) throw Error("dependency '%s' of '%s' does not exist, and substitution is disabled", worker.store.printStorePath(i), worker.store.printStorePath(drvPath)); addWaitee(upcast_goal(worker.makePathSubstitutionGoal(i))); } if (!waitees.empty()) co_await Suspend{}; /* to prevent hang (no wake-up event) */ co_return inputsRealised(); } Goal::Co DerivationGoal::repairClosure() { assert(!drv->type().isImpure()); /* If we're repairing, we now know that our own outputs are valid. Now check whether the other paths in the outputs closure are good. If not, then start derivation goals for the derivations that produced those outputs. */ /* Get the output closure. */ auto outputs = queryDerivationOutputMap(); StorePathSet outputClosure; for (auto & i : outputs) { if (!wantedOutputs.contains(i.first)) continue; worker.store.computeFSClosure(i.second, outputClosure); } /* Filter out our own outputs (which we have already checked). */ for (auto & i : outputs) outputClosure.erase(i.second); /* Get all dependencies of this derivation so that we know which derivation is responsible for which path in the output closure. */ StorePathSet inputClosure; if (useDerivation) worker.store.computeFSClosure(drvPath, inputClosure); std::map<StorePath, StorePath> outputsToDrv; for (auto & i : inputClosure) if (i.isDerivation()) { auto depOutputs = worker.store.queryPartialDerivationOutputMap(i, &worker.evalStore); for (auto & j : depOutputs) if (j.second) outputsToDrv.insert_or_assign(*j.second, i); } /* Check each path (slow!). */ for (auto & i : outputClosure) { if (worker.pathContentsGood(i)) continue; printError( "found corrupted or missing path '%s' in the output closure of '%s'", worker.store.printStorePath(i), worker.store.printStorePath(drvPath)); auto drvPath2 = outputsToDrv.find(i); if (drvPath2 == outputsToDrv.end()) addWaitee(upcast_goal(worker.makePathSubstitutionGoal(i, Repair))); else addWaitee(worker.makeGoal( DerivedPath::Built { .drvPath = makeConstantStorePathRef(drvPath2->second), .outputs = OutputsSpec::All { }, }, bmRepair)); } if (waitees.empty()) { co_return done(BuildResult::AlreadyValid, assertPathValidity()); } else { co_await Suspend{}; co_return closureRepaired(); } } Goal::Co DerivationGoal::closureRepaired() { trace("closure repaired"); if (nrFailed > 0) throw Error("some paths in the output closure of derivation '%s' could not be repaired", worker.store.printStorePath(drvPath)); co_return done(BuildResult::AlreadyValid, assertPathValidity()); } Goal::Co DerivationGoal::inputsRealised() { trace("all inputs realised"); if (nrFailed != 0) { if (!useDerivation) throw Error("some dependencies of '%s' are missing", worker.store.printStorePath(drvPath)); co_return done(BuildResult::DependencyFailed, {}, Error( "%s dependencies of derivation '%s' failed to build", nrFailed, worker.store.printStorePath(drvPath))); } if (retrySubstitution == RetrySubstitution::YesNeed) { retrySubstitution = RetrySubstitution::AlreadyRetried; co_return haveDerivation(); } /* Gather information necessary for computing the closure and/or running the build hook. */ /* Determine the full set of input paths. */ /* First, the input derivations. */ if (useDerivation) { auto & fullDrv = *dynamic_cast<Derivation *>(drv.get()); auto drvType = fullDrv.type(); bool resolveDrv = std::visit(overloaded { [&](const DerivationType::InputAddressed & ia) { /* must resolve if deferred. */ return ia.deferred; }, [&](const DerivationType::ContentAddressed & ca) { return !fullDrv.inputDrvs.map.empty() && ( ca.fixed /* Can optionally resolve if fixed, which is good for avoiding unnecessary rebuilds. */ ? experimentalFeatureSettings.isEnabled(Xp::CaDerivations) /* Must resolve if floating and there are any inputs drvs. */ : true); }, [&](const DerivationType::Impure &) { return true; } }, drvType.raw); if (resolveDrv && !fullDrv.inputDrvs.map.empty()) { experimentalFeatureSettings.require(Xp::CaDerivations); /* We are be able to resolve this derivation based on the now-known results of dependencies. If so, we become a stub goal aliasing that resolved derivation goal. */ std::optional attempt = fullDrv.tryResolve(worker.store, inputDrvOutputs); if (!attempt) { /* TODO (impure derivations-induced tech debt) (see below): The above attempt should have found it, but because we manage inputDrvOutputs statefully, sometimes it gets out of sync with the real source of truth (store). So we query the store directly if there's a problem. */ attempt = fullDrv.tryResolve(worker.store, &worker.evalStore); } assert(attempt); Derivation drvResolved { std::move(*attempt) }; auto pathResolved = writeDerivation(worker.store, drvResolved); auto msg = fmt("resolved derivation: '%s' -> '%s'", worker.store.printStorePath(drvPath), worker.store.printStorePath(pathResolved)); act = std::make_unique<Activity>(*logger, lvlInfo, actBuildWaiting, msg, Logger::Fields { worker.store.printStorePath(drvPath), worker.store.printStorePath(pathResolved), }); resolvedDrvGoal = worker.makeDerivationGoal( pathResolved, wantedOutputs, buildMode); addWaitee(resolvedDrvGoal); co_await Suspend{}; co_return resolvedFinished(); } std::function<void(const StorePath &, const DerivedPathMap<StringSet>::ChildNode &)> accumInputPaths; accumInputPaths = [&](const StorePath & depDrvPath, const DerivedPathMap<StringSet>::ChildNode & inputNode) { /* Add the relevant output closures of the input derivation `i' as input paths. Only add the closures of output paths that are specified as inputs. */ auto getOutput = [&](const std::string & outputName) { /* TODO (impure derivations-induced tech debt): Tracking input derivation outputs statefully through the goals is error prone and has led to bugs. For a robust nix, we need to move towards the `else` branch, which does not rely on goal state to match up with the reality of the store, which is our real source of truth. However, the impure derivations feature still relies on this fragile way of doing things, because its builds do not have a representation in the store, which is a usability problem in itself. When implementing this logic entirely with lookups make sure that they're cached. */ if (auto outPath = get(inputDrvOutputs, { depDrvPath, outputName })) { return *outPath; } else { auto outMap = [&]{ for (auto * drvStore : { &worker.evalStore, &worker.store }) if (drvStore->isValidPath(depDrvPath)) return worker.store.queryDerivationOutputMap(depDrvPath, drvStore); assert(false); }(); auto outMapPath = outMap.find(outputName); if (outMapPath == outMap.end()) { throw Error( "derivation '%s' requires non-existent output '%s' from input derivation '%s'", worker.store.printStorePath(drvPath), outputName, worker.store.printStorePath(depDrvPath)); } return outMapPath->second; } }; for (auto & outputName : inputNode.value) worker.store.computeFSClosure(getOutput(outputName), inputPaths); for (auto & [outputName, childNode] : inputNode.childMap) accumInputPaths(getOutput(outputName), childNode); }; for (auto & [depDrvPath, depNode] : fullDrv.inputDrvs.map) accumInputPaths(depDrvPath, depNode); } /* Second, the input sources. */ worker.store.computeFSClosure(drv->inputSrcs, inputPaths); debug("added input paths %s", worker.store.showPaths(inputPaths)); /* What type of derivation are we building? */ derivationType = drv->type(); /* Okay, try to build. Note that here we don't wait for a build slot to become available, since we don't need one if there is a build hook. */ worker.wakeUp(shared_from_this()); co_await Suspend{}; co_return tryToBuild(); } void DerivationGoal::started() { auto msg = fmt( buildMode == bmRepair ? "repairing outputs of '%s'" : buildMode == bmCheck ? "checking outputs of '%s'" : "building '%s'", worker.store.printStorePath(drvPath)); fmt("building '%s'", worker.store.printStorePath(drvPath)); #ifndef _WIN32 // TODO enable build hook on Windows if (hook) msg += fmt(" on '%s'", machineName); #endif act = std::make_unique<Activity>(*logger, lvlInfo, actBuild, msg, Logger::Fields{worker.store.printStorePath(drvPath), #ifndef _WIN32 // TODO enable build hook on Windows hook ? machineName : #endif "", 1, 1}); mcRunningBuilds = std::make_unique<MaintainCount<uint64_t>>(worker.runningBuilds); worker.updateProgress(); } Goal::Co DerivationGoal::tryToBuild() { trace("trying to build"); /* Obtain locks on all output paths, if the paths are known a priori. The locks are automatically released when we exit this function or Nix crashes. If we can't acquire the lock, then continue; hopefully some other goal can start a build, and if not, the main loop will sleep a few seconds and then retry this goal. */ PathSet lockFiles; /* FIXME: Should lock something like the drv itself so we don't build same CA drv concurrently */ if (dynamic_cast<LocalStore *>(&worker.store)) { /* If we aren't a local store, we might need to use the local store as a build remote, but that would cause a deadlock. */ /* FIXME: Make it so we can use ourselves as a build remote even if we are the local store (separate locking for building vs scheduling? */ /* FIXME: find some way to lock for scheduling for the other stores so a forking daemon with --store still won't farm out redundant builds. */ for (auto & i : drv->outputsAndOptPaths(worker.store)) { if (i.second.second) lockFiles.insert(worker.store.Store::toRealPath(*i.second.second)); else lockFiles.insert( worker.store.Store::toRealPath(drvPath) + "." + i.first ); } } if (!outputLocks.lockPaths(lockFiles, "", false)) { if (!actLock) actLock = std::make_unique<Activity>(*logger, lvlWarn, actBuildWaiting, fmt("waiting for lock on %s", Magenta(showPaths(lockFiles)))); worker.waitForAWhile(shared_from_this()); co_await Suspend{}; co_return tryToBuild(); } actLock.reset(); /* Now check again whether the outputs are valid. This is because another process may have started building in parallel. After it has finished and released the locks, we can (and should) reuse its results. (Strictly speaking the first check can be omitted, but that would be less efficient.) Note that since we now hold the locks on the output paths, no other process can build this derivation, so no further checks are necessary. */ auto [allValid, validOutputs] = checkPathValidity(); if (buildMode != bmCheck && allValid) { debug("skipping build of derivation '%s', someone beat us to it", worker.store.printStorePath(drvPath)); outputLocks.setDeletion(true); co_return done(BuildResult::AlreadyValid, std::move(validOutputs)); } /* If any of the outputs already exist but are not valid, delete them. */ for (auto & [_, status] : initialOutputs) { if (!status.known || status.known->isValid()) continue; auto storePath = status.known->path; debug("removing invalid path '%s'", worker.store.printStorePath(status.known->path)); deletePath(worker.store.Store::toRealPath(storePath)); } /* Don't do a remote build if the derivation has the attribute `preferLocalBuild' set. Also, check and repair modes are only supported for local builds. */ bool buildLocally = (buildMode != bmNormal || parsedDrv->willBuildLocally(worker.store)) && settings.maxBuildJobs.get() != 0; if (!buildLocally) { switch (tryBuildHook()) { case rpAccept: /* Yes, it has started doing so. Wait until we get EOF from the hook. */ actLock.reset(); buildResult.startTime = time(0); // inexact started(); co_await Suspend{}; co_return buildDone(); case rpPostpone: /* Not now; wait until at least one child finishes or the wake-up timeout expires. */ if (!actLock) actLock = std::make_unique<Activity>(*logger, lvlWarn, actBuildWaiting, fmt("waiting for a machine to build '%s'", Magenta(worker.store.printStorePath(drvPath)))); worker.waitForAWhile(shared_from_this()); outputLocks.unlock(); co_await Suspend{}; co_return tryToBuild(); case rpDecline: /* We should do it ourselves. */ break; } } actLock.reset(); worker.wakeUp(shared_from_this()); co_await Suspend{}; co_return tryLocalBuild(); } Goal::Co DerivationGoal::tryLocalBuild() { throw Error( R"( Unable to build with a primary store that isn't a local store; either pass a different '--store' or enable remote builds. For more information check 'man nix.conf' and search for '/machines'. )" ); } static void chmod_(const Path & path, mode_t mode) { if (chmod(path.c_str(), mode) == -1) throw SysError("setting permissions on '%s'", path); } /* Move/rename path 'src' to 'dst'. Temporarily make 'src' writable if it's a directory and we're not root (to be able to update the directory's parent link ".."). */ static void movePath(const Path & src, const Path & dst) { auto st = lstat(src); bool changePerm = ( #ifndef _WIN32 geteuid() #else !isRootUser() #endif && S_ISDIR(st.st_mode) && !(st.st_mode & S_IWUSR)); if (changePerm) chmod_(src, st.st_mode | S_IWUSR); std::filesystem::rename(src, dst); if (changePerm) chmod_(dst, st.st_mode); } void replaceValidPath(const Path & storePath, const Path & tmpPath) { /* We can't atomically replace storePath (the original) with tmpPath (the replacement), so we have to move it out of the way first. We'd better not be interrupted here, because if we're repairing (say) Glibc, we end up with a broken system. */ Path oldPath = fmt("%1%.old-%2%-%3%", storePath, getpid(), rand()); if (pathExists(storePath)) movePath(storePath, oldPath); try { movePath(tmpPath, storePath); } catch (...) { try { // attempt to recover movePath(oldPath, storePath); } catch (...) { ignoreExceptionExceptInterrupt(); } throw; } deletePath(oldPath); } int DerivationGoal::getChildStatus() { #ifndef _WIN32 // TODO enable build hook on Windows return hook->pid.kill(); #else return 0; #endif } void DerivationGoal::closeReadPipes() { #ifndef _WIN32 // TODO enable build hook on Windows hook->builderOut.readSide.close(); hook->fromHook.readSide.close(); #endif } void DerivationGoal::cleanupHookFinally() { } void DerivationGoal::cleanupPreChildKill() { } void DerivationGoal::cleanupPostChildKill() { } bool DerivationGoal::cleanupDecideWhetherDiskFull() { return false; } void DerivationGoal::cleanupPostOutputsRegisteredModeCheck() { } void DerivationGoal::cleanupPostOutputsRegisteredModeNonCheck() { } void runPostBuildHook( Store & store, Logger & logger, const StorePath & drvPath, const StorePathSet & outputPaths) { auto hook = settings.postBuildHook; if (hook == "") return; Activity act(logger, lvlTalkative, actPostBuildHook, fmt("running post-build-hook '%s'", settings.postBuildHook), Logger::Fields{store.printStorePath(drvPath)}); PushActivity pact(act.id); std::map<std::string, std::string> hookEnvironment = getEnv(); hookEnvironment.emplace("DRV_PATH", store.printStorePath(drvPath)); hookEnvironment.emplace("OUT_PATHS", chomp(concatStringsSep(" ", store.printStorePathSet(outputPaths)))); hookEnvironment.emplace("NIX_CONFIG", globalConfig.toKeyValue()); struct LogSink : Sink { Activity & act; std::string currentLine; LogSink(Activity & act) : act(act) { } void operator() (std::string_view data) override { for (auto c : data) { if (c == '\n') { flushLine(); } else { currentLine += c; } } } void flushLine() { act.result(resPostBuildLogLine, currentLine); currentLine.clear(); } ~LogSink() { if (currentLine != "") { currentLine += '\n'; flushLine(); } } }; LogSink sink(act); runProgram2({ .program = settings.postBuildHook, .environment = hookEnvironment, .standardOut = &sink, .mergeStderrToStdout = true, }); } Goal::Co DerivationGoal::buildDone() { trace("build done"); Finally releaseBuildUser([&](){ this->cleanupHookFinally(); }); cleanupPreChildKill(); /* Since we got an EOF on the logger pipe, the builder is presumed to have terminated. In fact, the builder could also have simply have closed its end of the pipe, so just to be sure, kill it. */ int status = getChildStatus(); debug("builder process for '%s' finished", worker.store.printStorePath(drvPath)); buildResult.timesBuilt++; buildResult.stopTime = time(0); /* So the child is gone now. */ worker.childTerminated(this); /* Close the read side of the logger pipe. */ closeReadPipes(); /* Close the log file. */ closeLogFile(); cleanupPostChildKill(); if (buildResult.cpuUser && buildResult.cpuSystem) { debug("builder for '%s' terminated with status %d, user CPU %.3fs, system CPU %.3fs", worker.store.printStorePath(drvPath), status, ((double) buildResult.cpuUser->count()) / 1000000, ((double) buildResult.cpuSystem->count()) / 1000000); } bool diskFull = false; try { /* Check the exit status. */ if (!statusOk(status)) { diskFull |= cleanupDecideWhetherDiskFull(); auto msg = fmt("builder for '%s' %s", Magenta(worker.store.printStorePath(drvPath)), statusToString(status)); if (!logger->isVerbose() && !logTail.empty()) { msg += fmt(";\nlast %d log lines:\n", logTail.size()); for (auto & line : logTail) { msg += "> "; msg += line; msg += "\n"; } auto nixLogCommand = experimentalFeatureSettings.isEnabled(Xp::NixCommand) ? "nix log" : "nix-store -l"; msg += fmt("For full logs, run '" ANSI_BOLD "%s %s" ANSI_NORMAL "'.", nixLogCommand, worker.store.printStorePath(drvPath)); } if (diskFull) msg += "\nnote: build failure may have been caused by lack of free disk space"; throw BuildError(msg); } /* Compute the FS closure of the outputs and register them as being valid. */ auto builtOutputs = registerOutputs(); StorePathSet outputPaths; for (auto & [_, output] : builtOutputs) outputPaths.insert(output.outPath); runPostBuildHook( worker.store, *logger, drvPath, outputPaths ); cleanupPostOutputsRegisteredModeNonCheck(); /* It is now safe to delete the lock files, since all future lockers will see that the output paths are valid; they will not create new lock files with the same names as the old (unlinked) lock files. */ outputLocks.setDeletion(true); outputLocks.unlock(); co_return done(BuildResult::Built, std::move(builtOutputs)); } catch (BuildError & e) { outputLocks.unlock(); BuildResult::Status st = BuildResult::MiscFailure; #ifndef _WIN32 // TODO abstract over proc exit status if (hook && WIFEXITED(status) && WEXITSTATUS(status) == 101) st = BuildResult::TimedOut; else if (hook && (!WIFEXITED(status) || WEXITSTATUS(status) != 100)) { } else #endif { assert(derivationType); st = dynamic_cast<NotDeterministic*>(&e) ? BuildResult::NotDeterministic : statusOk(status) ? BuildResult::OutputRejected : !derivationType->isSandboxed() || diskFull ? BuildResult::TransientFailure : BuildResult::PermanentFailure; } co_return done(st, {}, std::move(e)); } } Goal::Co DerivationGoal::resolvedFinished() { trace("resolved derivation finished"); assert(resolvedDrvGoal); auto resolvedDrv = *resolvedDrvGoal->drv; auto & resolvedResult = resolvedDrvGoal->buildResult; SingleDrvOutputs builtOutputs; if (resolvedResult.success()) { auto resolvedHashes = staticOutputHashes(worker.store, resolvedDrv); StorePathSet outputPaths; for (auto & outputName : resolvedDrv.outputNames()) { auto initialOutput = get(initialOutputs, outputName); auto resolvedHash = get(resolvedHashes, outputName); if ((!initialOutput) || (!resolvedHash)) throw Error( "derivation '%s' doesn't have expected output '%s' (derivation-goal.cc/resolvedFinished,resolve)", worker.store.printStorePath(drvPath), outputName); auto realisation = [&]{ auto take1 = get(resolvedResult.builtOutputs, outputName); if (take1) return *take1; /* The above `get` should work. But sateful tracking of outputs in resolvedResult, this can get out of sync with the store, which is our actual source of truth. For now we just check the store directly if it fails. */ auto take2 = worker.evalStore.queryRealisation(DrvOutput { *resolvedHash, outputName }); if (take2) return *take2; throw Error( "derivation '%s' doesn't have expected output '%s' (derivation-goal.cc/resolvedFinished,realisation)", worker.store.printStorePath(resolvedDrvGoal->drvPath), outputName); }(); if (!drv->type().isImpure()) { auto newRealisation = realisation; newRealisation.id = DrvOutput { initialOutput->outputHash, outputName }; newRealisation.signatures.clear(); if (!drv->type().isFixed()) { auto & drvStore = worker.evalStore.isValidPath(drvPath) ? worker.evalStore : worker.store; newRealisation.dependentRealisations = drvOutputReferences(worker.store, *drv, realisation.outPath, &drvStore); } signRealisation(newRealisation); worker.store.registerDrvOutput(newRealisation); } outputPaths.insert(realisation.outPath); builtOutputs.emplace(outputName, realisation); } runPostBuildHook( worker.store, *logger, drvPath, outputPaths ); } auto status = resolvedResult.status; if (status == BuildResult::AlreadyValid) status = BuildResult::ResolvesToAlreadyValid; co_return done(status, std::move(builtOutputs)); } HookReply DerivationGoal::tryBuildHook() { #ifdef _WIN32 // TODO enable build hook on Windows return rpDecline; #else if (settings.buildHook.get().empty() || !worker.tryBuildHook || !useDerivation) return rpDecline; if (!worker.hook) worker.hook = std::make_unique<HookInstance>(); try { /* Send the request to the hook. */ worker.hook->sink << "try" << (worker.getNrLocalBuilds() < settings.maxBuildJobs ? 1 : 0) << drv->platform << worker.store.printStorePath(drvPath) << parsedDrv->getRequiredSystemFeatures(); worker.hook->sink.flush(); /* Read the first line of input, which should be a word indicating whether the hook wishes to perform the build. */ std::string reply; while (true) { auto s = [&]() { try { return readLine(worker.hook->fromHook.readSide.get()); } catch (Error & e) { e.addTrace({}, "while reading the response from the build hook"); throw; } }(); if (handleJSONLogMessage(s, worker.act, worker.hook->activities, true)) ; else if (s.substr(0, 2) == "# ") { reply = s.substr(2); break; } else { s += "\n"; writeToStderr(s); } } debug("hook reply is '%1%'", reply); if (reply == "decline") return rpDecline; else if (reply == "decline-permanently") { worker.tryBuildHook = false; worker.hook = 0; return rpDecline; } else if (reply == "postpone") return rpPostpone; else if (reply != "accept") throw Error("bad hook reply '%s'", reply); } catch (SysError & e) { if (e.errNo == EPIPE) { printError( "build hook died unexpectedly: %s", chomp(drainFD(worker.hook->fromHook.readSide.get()))); worker.hook = 0; return rpDecline; } else throw; } hook = std::move(worker.hook); try { machineName = readLine(hook->fromHook.readSide.get()); } catch (Error & e) { e.addTrace({}, "while reading the machine name from the build hook"); throw; } CommonProto::WriteConn conn { hook->sink }; /* Tell the hook all the inputs that have to be copied to the remote system. */ CommonProto::write(worker.store, conn, inputPaths); /* Tell the hooks the missing outputs that have to be copied back from the remote system. */ { StringSet missingOutputs; for (auto & [outputName, status] : initialOutputs) { // XXX: Does this include known CA outputs? if (buildMode != bmCheck && status.known && status.known->isValid()) continue; missingOutputs.insert(outputName); } CommonProto::write(worker.store, conn, missingOutputs); } hook->sink = FdSink(); hook->toHook.writeSide.close(); /* Create the log file and pipe. */ Path logFile = openLogFile(); std::set<MuxablePipePollState::CommChannel> fds; fds.insert(hook->fromHook.readSide.get()); fds.insert(hook->builderOut.readSide.get()); worker.childStarted(shared_from_this(), fds, false, false); return rpAccept; #endif } SingleDrvOutputs DerivationGoal::registerOutputs() { /* When using a build hook, the build hook can register the output as valid (by doing `nix-store --import'). If so we don't have to do anything here. We can only early return when the outputs are known a priori. For floating content-addressed derivations this isn't the case. */ return assertPathValidity(); } Path DerivationGoal::openLogFile() { logSize = 0; if (!settings.keepLog) return ""; auto baseName = std::string(baseNameOf(worker.store.printStorePath(drvPath))); /* Create a log file. */ Path logDir; if (auto localStore = dynamic_cast<LocalStore *>(&worker.store)) logDir = localStore->logDir; else logDir = settings.nixLogDir; Path dir = fmt("%s/%s/%s/", logDir, LocalFSStore::drvsLogDir, baseName.substr(0, 2)); createDirs(dir); Path logFileName = fmt("%s/%s%s", dir, baseName.substr(2), settings.compressLog ? ".bz2" : ""); fdLogFile = toDescriptor(open(logFileName.c_str(), O_CREAT | O_WRONLY | O_TRUNC #ifndef _WIN32 | O_CLOEXEC #endif , 0666)); if (!fdLogFile) throw SysError("creating log file '%1%'", logFileName); logFileSink = std::make_shared<FdSink>(fdLogFile.get()); if (settings.compressLog) logSink = std::shared_ptr<CompressionSink>(makeCompressionSink("bzip2", *logFileSink)); else logSink = logFileSink; return logFileName; } void DerivationGoal::closeLogFile() { auto logSink2 = std::dynamic_pointer_cast<CompressionSink>(logSink); if (logSink2) logSink2->finish(); if (logFileSink) logFileSink->flush(); logSink = logFileSink = 0; fdLogFile.close(); } bool DerivationGoal::isReadDesc(Descriptor fd) { #ifdef _WIN32 // TODO enable build hook on Windows return false; #else return fd == hook->builderOut.readSide.get(); #endif } void DerivationGoal::handleChildOutput(Descriptor fd, std::string_view data) { // local & `ssh://`-builds are dealt with here. auto isWrittenToLog = isReadDesc(fd); if (isWrittenToLog) { logSize += data.size(); if (settings.maxLogSize && logSize > settings.maxLogSize) { killChild(); // We're not inside a coroutine, hence we can't use co_return here. // Thus we ignore the return value. [[maybe_unused]] Done _ = done( BuildResult::LogLimitExceeded, {}, Error("%s killed after writing more than %d bytes of log output", getName(), settings.maxLogSize)); return; } for (auto c : data) if (c == '\r') currentLogLinePos = 0; else if (c == '\n') flushLine(); else { if (currentLogLinePos >= currentLogLine.size()) currentLogLine.resize(currentLogLinePos + 1); currentLogLine[currentLogLinePos++] = c; } if (logSink) (*logSink)(data); } #ifndef _WIN32 // TODO enable build hook on Windows if (hook && fd == hook->fromHook.readSide.get()) { for (auto c : data) if (c == '\n') { auto json = parseJSONMessage(currentHookLine); if (json) { auto s = handleJSONLogMessage(*json, worker.act, hook->activities, true); // ensure that logs from a builder using `ssh-ng://` as protocol // are also available to `nix log`. if (s && !isWrittenToLog && logSink) { const auto type = (*json)["type"]; const auto fields = (*json)["fields"]; if (type == resBuildLogLine) { (*logSink)((fields.size() > 0 ? fields[0].get<std::string>() : "") + "\n"); } else if (type == resSetPhase && ! fields.is_null()) { const auto phase = fields[0]; if (! phase.is_null()) { // nixpkgs' stdenv produces lines in the log to signal // phase changes. // We want to get the same lines in case of remote builds. // The format is: // @nix { "action": "setPhase", "phase": "$curPhase" } const auto logLine = nlohmann::json::object({ {"action", "setPhase"}, {"phase", phase} }); (*logSink)("@nix " + logLine.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace) + "\n"); } } } } currentHookLine.clear(); } else currentHookLine += c; } #endif } void DerivationGoal::handleEOF(Descriptor fd) { if (!currentLogLine.empty()) flushLine(); worker.wakeUp(shared_from_this()); } void DerivationGoal::flushLine() { if (handleJSONLogMessage(currentLogLine, *act, builderActivities, false)) ; else { logTail.push_back(currentLogLine); if (logTail.size() > settings.logLines) logTail.pop_front(); act->result(resBuildLogLine, currentLogLine); } currentLogLine = ""; currentLogLinePos = 0; } std::map<std::string, std::optional<StorePath>> DerivationGoal::queryPartialDerivationOutputMap() { assert(!drv->type().isImpure()); if (!useDerivation || drv->type().hasKnownOutputPaths()) { std::map<std::string, std::optional<StorePath>> res; for (auto & [name, output] : drv->outputs) res.insert_or_assign(name, output.path(worker.store, drv->name, name)); return res; } else { for (auto * drvStore : { &worker.evalStore, &worker.store }) if (drvStore->isValidPath(drvPath)) return worker.store.queryPartialDerivationOutputMap(drvPath, drvStore); assert(false); } } OutputPathMap DerivationGoal::queryDerivationOutputMap() { assert(!drv->type().isImpure()); if (!useDerivation || drv->type().hasKnownOutputPaths()) { OutputPathMap res; for (auto & [name, output] : drv->outputsAndOptPaths(worker.store)) res.insert_or_assign(name, *output.second); return res; } else { for (auto * drvStore : { &worker.evalStore, &worker.store }) if (drvStore->isValidPath(drvPath)) return worker.store.queryDerivationOutputMap(drvPath, drvStore); assert(false); } } std::pair<bool, SingleDrvOutputs> DerivationGoal::checkPathValidity() { if (drv->type().isImpure()) return { false, {} }; bool checkHash = buildMode == bmRepair; auto wantedOutputsLeft = std::visit(overloaded { [&](const OutputsSpec::All &) { return StringSet {}; }, [&](const OutputsSpec::Names & names) { return static_cast<StringSet>(names); }, }, wantedOutputs.raw); SingleDrvOutputs validOutputs; for (auto & i : queryPartialDerivationOutputMap()) { auto initialOutput = get(initialOutputs, i.first); if (!initialOutput) // this is an invalid output, gets catched with (!wantedOutputsLeft.empty()) continue; auto & info = *initialOutput; info.wanted = wantedOutputs.contains(i.first); if (info.wanted) wantedOutputsLeft.erase(i.first); if (i.second) { auto outputPath = *i.second; info.known = { .path = outputPath, .status = !worker.store.isValidPath(outputPath) ? PathStatus::Absent : !checkHash || worker.pathContentsGood(outputPath) ? PathStatus::Valid : PathStatus::Corrupt, }; } auto drvOutput = DrvOutput{info.outputHash, i.first}; if (experimentalFeatureSettings.isEnabled(Xp::CaDerivations)) { if (auto real = worker.store.queryRealisation(drvOutput)) { info.known = { .path = real->outPath, .status = PathStatus::Valid, }; } else if (info.known && info.known->isValid()) { // We know the output because it's a static output of the // derivation, and the output path is valid, but we don't have // its realisation stored (probably because it has been built // without the `ca-derivations` experimental flag). worker.store.registerDrvOutput( Realisation { drvOutput, info.known->path, } ); } } if (info.known && info.known->isValid()) validOutputs.emplace(i.first, Realisation { drvOutput, info.known->path }); } // If we requested all the outputs, we are always fine. // If we requested specific elements, the loop above removes all the valid // ones, so any that are left must be invalid. if (!wantedOutputsLeft.empty()) throw Error("derivation '%s' does not have wanted outputs %s", worker.store.printStorePath(drvPath), concatStringsSep(", ", quoteStrings(wantedOutputsLeft))); bool allValid = true; for (auto & [_, status] : initialOutputs) { if (!status.wanted) continue; if (!status.known || !status.known->isValid()) { allValid = false; break; } } return { allValid, validOutputs }; } SingleDrvOutputs DerivationGoal::assertPathValidity() { auto [allValid, validOutputs] = checkPathValidity(); if (!allValid) throw Error("some outputs are unexpectedly invalid"); return validOutputs; } Goal::Done DerivationGoal::done( BuildResult::Status status, SingleDrvOutputs builtOutputs, std::optional<Error> ex) { outputLocks.unlock(); buildResult.status = status; if (ex) buildResult.errorMsg = fmt("%s", Uncolored(ex->info().msg)); if (buildResult.status == BuildResult::TimedOut) worker.timedOut = true; if (buildResult.status == BuildResult::PermanentFailure) worker.permanentFailure = true; mcExpectedBuilds.reset(); mcRunningBuilds.reset(); if (buildResult.success()) { auto wantedBuiltOutputs = filterDrvOutputs(wantedOutputs, std::move(builtOutputs)); assert(!wantedBuiltOutputs.empty()); buildResult.builtOutputs = std::move(wantedBuiltOutputs); if (status == BuildResult::Built) worker.doneBuilds++; } else { if (status != BuildResult::DependencyFailed) worker.failedBuilds++; } worker.updateProgress(); auto traceBuiltOutputsFile = getEnv("_NIX_TRACE_BUILT_OUTPUTS").value_or(""); if (traceBuiltOutputsFile != "") { std::fstream fs; fs.open(traceBuiltOutputsFile, std::fstream::out); fs << worker.store.printStorePath(drvPath) << "\t" << buildResult.toString() << std::endl; } return amDone(buildResult.success() ? ecSuccess : ecFailed, std::move(ex)); } void DerivationGoal::waiteeDone(GoalPtr waitee, ExitCode result) { Goal::waiteeDone(waitee, result); if (!useDerivation || !drv) return; auto & fullDrv = *dynamic_cast<Derivation *>(drv.get()); auto * dg = dynamic_cast<DerivationGoal *>(&*waitee); if (!dg) return; auto * nodeP = fullDrv.inputDrvs.findSlot(DerivedPath::Opaque { .path = dg->drvPath }); if (!nodeP) return; auto & outputs = nodeP->value; for (auto & outputName : outputs) { auto buildResult = dg->getBuildResult(DerivedPath::Built { .drvPath = makeConstantStorePathRef(dg->drvPath), .outputs = OutputsSpec::Names { outputName }, }); if (buildResult.success()) { auto i = buildResult.builtOutputs.find(outputName); if (i != buildResult.builtOutputs.end()) inputDrvOutputs.insert_or_assign( { dg->drvPath, outputName }, i->second.outPath); } } } }
55,859
C++
.cc
1,328
32.496235
173
0.608197
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,855
entry-points.cc
NixOS_nix/src/libstore/build/entry-points.cc
#include "worker.hh" #include "substitution-goal.hh" #ifndef _WIN32 // TODO Enable building on Windows # include "derivation-goal.hh" #endif #include "local-store.hh" #include "strings.hh" namespace nix { void Store::buildPaths(const std::vector<DerivedPath> & reqs, BuildMode buildMode, std::shared_ptr<Store> evalStore) { Worker worker(*this, evalStore ? *evalStore : *this); Goals goals; for (auto & br : reqs) goals.insert(worker.makeGoal(br, buildMode)); worker.run(goals); StringSet failed; std::optional<Error> ex; for (auto & i : goals) { if (i->ex) { if (ex) logError(i->ex->info()); else ex = std::move(i->ex); } if (i->exitCode != Goal::ecSuccess) { #ifndef _WIN32 // TODO Enable building on Windows if (auto i2 = dynamic_cast<DerivationGoal *>(i.get())) failed.insert(printStorePath(i2->drvPath)); else #endif if (auto i2 = dynamic_cast<PathSubstitutionGoal *>(i.get())) failed.insert(printStorePath(i2->storePath)); } } if (failed.size() == 1 && ex) { ex->withExitStatus(worker.failingExitStatus()); throw std::move(*ex); } else if (!failed.empty()) { if (ex) logError(ex->info()); throw Error(worker.failingExitStatus(), "build of %s failed", concatStringsSep(", ", quoteStrings(failed))); } } std::vector<KeyedBuildResult> Store::buildPathsWithResults( const std::vector<DerivedPath> & reqs, BuildMode buildMode, std::shared_ptr<Store> evalStore) { Worker worker(*this, evalStore ? *evalStore : *this); Goals goals; std::vector<std::pair<const DerivedPath &, GoalPtr>> state; for (const auto & req : reqs) { auto goal = worker.makeGoal(req, buildMode); goals.insert(goal); state.push_back({req, goal}); } worker.run(goals); std::vector<KeyedBuildResult> results; results.reserve(state.size()); for (auto & [req, goalPtr] : state) results.emplace_back(KeyedBuildResult { goalPtr->getBuildResult(req), /* .path = */ req, }); return results; } BuildResult Store::buildDerivation(const StorePath & drvPath, const BasicDerivation & drv, BuildMode buildMode) { Worker worker(*this, *this); #ifndef _WIN32 // TODO Enable building on Windows auto goal = worker.makeBasicDerivationGoal(drvPath, drv, OutputsSpec::All {}, buildMode); #else std::shared_ptr<Goal> goal; throw UnimplementedError("Building derivations not yet implemented on windows."); #endif try { worker.run(Goals{goal}); return goal->getBuildResult(DerivedPath::Built { .drvPath = makeConstantStorePathRef(drvPath), .outputs = OutputsSpec::All {}, }); } catch (Error & e) { return BuildResult { .status = BuildResult::MiscFailure, .errorMsg = e.msg(), }; }; } void Store::ensurePath(const StorePath & path) { /* If the path is already valid, we're done. */ if (isValidPath(path)) return; Worker worker(*this, *this); GoalPtr goal = worker.makePathSubstitutionGoal(path); Goals goals = {goal}; worker.run(goals); if (goal->exitCode != Goal::ecSuccess) { if (goal->ex) { goal->ex->withExitStatus(worker.failingExitStatus()); throw std::move(*goal->ex); } else throw Error(worker.failingExitStatus(), "path '%s' does not exist and cannot be created", printStorePath(path)); } } void Store::repairPath(const StorePath & path) { Worker worker(*this, *this); GoalPtr goal = worker.makePathSubstitutionGoal(path, Repair); Goals goals = {goal}; worker.run(goals); if (goal->exitCode != Goal::ecSuccess) { /* Since substituting the path didn't work, if we have a valid deriver, then rebuild the deriver. */ auto info = queryPathInfo(path); if (info->deriver && isValidPath(*info->deriver)) { goals.clear(); goals.insert(worker.makeGoal(DerivedPath::Built { .drvPath = makeConstantStorePathRef(*info->deriver), // FIXME: Should just build the specific output we need. .outputs = OutputsSpec::All { }, }, bmRepair)); worker.run(goals); } else throw Error(worker.failingExitStatus(), "cannot repair path '%s'", printStorePath(path)); } } }
4,561
C++
.cc
127
28.929134
124
0.623044
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,856
drv-output-substitution-goal.cc
NixOS_nix/src/libstore/build/drv-output-substitution-goal.cc
#include "drv-output-substitution-goal.hh" #include "finally.hh" #include "worker.hh" #include "substitution-goal.hh" #include "callback.hh" namespace nix { DrvOutputSubstitutionGoal::DrvOutputSubstitutionGoal( const DrvOutput & id, Worker & worker, RepairFlag repair, std::optional<ContentAddress> ca) : Goal(worker, DerivedPath::Opaque { StorePath::dummy }) , id(id) { name = fmt("substitution of '%s'", id.to_string()); trace("created"); } Goal::Co DrvOutputSubstitutionGoal::init() { trace("init"); /* If the derivation already exists, we’re done */ if (worker.store.queryRealisation(id)) { co_return amDone(ecSuccess); } auto subs = settings.useSubstitutes ? getDefaultSubstituters() : std::list<ref<Store>>(); bool substituterFailed = false; for (auto sub : subs) { trace("trying next substituter"); /* The callback of the curl download below can outlive `this` (if some other error occurs), so it must not touch `this`. So put the shared state in a separate refcounted object. */ auto outPipe = std::make_shared<MuxablePipe>(); #ifndef _WIN32 outPipe->create(); #else outPipe->createAsyncPipe(worker.ioport.get()); #endif auto promise = std::make_shared<std::promise<std::shared_ptr<const Realisation>>>(); sub->queryRealisation( id, { [outPipe(outPipe), promise(promise)](std::future<std::shared_ptr<const Realisation>> res) { try { Finally updateStats([&]() { outPipe->writeSide.close(); }); promise->set_value(res.get()); } catch (...) { promise->set_exception(std::current_exception()); } } }); worker.childStarted(shared_from_this(), { #ifndef _WIN32 outPipe->readSide.get() #else &*outPipe #endif }, true, false); co_await Suspend{}; worker.childTerminated(this); /* * The realisation corresponding to the given output id. * Will be filled once we can get it. */ std::shared_ptr<const Realisation> outputInfo; try { outputInfo = promise->get_future().get(); } catch (std::exception & e) { printError(e.what()); substituterFailed = true; } if (!outputInfo) continue; bool failed = false; for (const auto & [depId, depPath] : outputInfo->dependentRealisations) { if (depId != id) { if (auto localOutputInfo = worker.store.queryRealisation(depId); localOutputInfo && localOutputInfo->outPath != depPath) { warn( "substituter '%s' has an incompatible realisation for '%s', ignoring.\n" "Local: %s\n" "Remote: %s", sub->getUri(), depId.to_string(), worker.store.printStorePath(localOutputInfo->outPath), worker.store.printStorePath(depPath) ); failed = true; break; } addWaitee(worker.makeDrvOutputSubstitutionGoal(depId)); } } if (failed) continue; co_return realisationFetched(outputInfo, sub); } /* None left. Terminate this goal and let someone else deal with it. */ debug("derivation output '%s' is required, but there is no substituter that can provide it", id.to_string()); if (substituterFailed) { worker.failedSubstitutions++; worker.updateProgress(); } /* Hack: don't indicate failure if there were no substituters. In that case the calling derivation should just do a build. */ co_return amDone(substituterFailed ? ecFailed : ecNoSubstituters); } Goal::Co DrvOutputSubstitutionGoal::realisationFetched(std::shared_ptr<const Realisation> outputInfo, nix::ref<nix::Store> sub) { addWaitee(worker.makePathSubstitutionGoal(outputInfo->outPath)); if (!waitees.empty()) co_await Suspend{}; trace("output path substituted"); if (nrFailed > 0) { debug("The output path of the derivation output '%s' could not be substituted", id.to_string()); co_return amDone(nrNoSubstituters > 0 || nrIncompleteClosure > 0 ? ecIncompleteClosure : ecFailed); } worker.store.registerDrvOutput(*outputInfo); trace("finished"); co_return amDone(ecSuccess); } std::string DrvOutputSubstitutionGoal::key() { /* "a$" ensures substitution goals happen before derivation goals. */ return "a$" + std::string(id.to_string()); } void DrvOutputSubstitutionGoal::handleEOF(Descriptor fd) { worker.wakeUp(shared_from_this()); } }
4,942
C++
.cc
127
29.826772
129
0.604058
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,857
worker.cc
NixOS_nix/src/libstore/build/worker.cc
#include "local-store.hh" #include "machines.hh" #include "worker.hh" #include "substitution-goal.hh" #include "drv-output-substitution-goal.hh" #include "derivation-goal.hh" #ifndef _WIN32 // TODO Enable building on Windows # include "local-derivation-goal.hh" # include "hook-instance.hh" #endif #include "signals.hh" namespace nix { Worker::Worker(Store & store, Store & evalStore) : act(*logger, actRealise) , actDerivations(*logger, actBuilds) , actSubstitutions(*logger, actCopyPaths) , store(store) , evalStore(evalStore) { nrLocalBuilds = 0; nrSubstitutions = 0; lastWokenUp = steady_time_point::min(); permanentFailure = false; timedOut = false; hashMismatch = false; checkMismatch = false; } Worker::~Worker() { /* Explicitly get rid of all strong pointers now. After this all goals that refer to this worker should be gone. (Otherwise we are in trouble, since goals may call childTerminated() etc. in their destructors). */ topGoals.clear(); assert(expectedSubstitutions == 0); assert(expectedDownloadSize == 0); assert(expectedNarSize == 0); } std::shared_ptr<DerivationGoal> Worker::makeDerivationGoalCommon( const StorePath & drvPath, const OutputsSpec & wantedOutputs, std::function<std::shared_ptr<DerivationGoal>()> mkDrvGoal) { std::weak_ptr<DerivationGoal> & goal_weak = derivationGoals[drvPath]; std::shared_ptr<DerivationGoal> goal = goal_weak.lock(); if (!goal) { goal = mkDrvGoal(); goal_weak = goal; wakeUp(goal); } else { goal->addWantedOutputs(wantedOutputs); } return goal; } std::shared_ptr<DerivationGoal> Worker::makeDerivationGoal(const StorePath & drvPath, const OutputsSpec & wantedOutputs, BuildMode buildMode) { return makeDerivationGoalCommon(drvPath, wantedOutputs, [&]() -> std::shared_ptr<DerivationGoal> { return #ifndef _WIN32 // TODO Enable building on Windows dynamic_cast<LocalStore *>(&store) ? std::make_shared<LocalDerivationGoal>(drvPath, wantedOutputs, *this, buildMode) : #endif std::make_shared</* */DerivationGoal>(drvPath, wantedOutputs, *this, buildMode); }); } std::shared_ptr<DerivationGoal> Worker::makeBasicDerivationGoal(const StorePath & drvPath, const BasicDerivation & drv, const OutputsSpec & wantedOutputs, BuildMode buildMode) { return makeDerivationGoalCommon(drvPath, wantedOutputs, [&]() -> std::shared_ptr<DerivationGoal> { return #ifndef _WIN32 // TODO Enable building on Windows dynamic_cast<LocalStore *>(&store) ? std::make_shared<LocalDerivationGoal>(drvPath, drv, wantedOutputs, *this, buildMode) : #endif std::make_shared</* */DerivationGoal>(drvPath, drv, wantedOutputs, *this, buildMode); }); } std::shared_ptr<PathSubstitutionGoal> Worker::makePathSubstitutionGoal(const StorePath & path, RepairFlag repair, std::optional<ContentAddress> ca) { std::weak_ptr<PathSubstitutionGoal> & goal_weak = substitutionGoals[path]; auto goal = goal_weak.lock(); // FIXME if (!goal) { goal = std::make_shared<PathSubstitutionGoal>(path, *this, repair, ca); goal_weak = goal; wakeUp(goal); } return goal; } std::shared_ptr<DrvOutputSubstitutionGoal> Worker::makeDrvOutputSubstitutionGoal(const DrvOutput& id, RepairFlag repair, std::optional<ContentAddress> ca) { std::weak_ptr<DrvOutputSubstitutionGoal> & goal_weak = drvOutputSubstitutionGoals[id]; auto goal = goal_weak.lock(); // FIXME if (!goal) { goal = std::make_shared<DrvOutputSubstitutionGoal>(id, *this, repair, ca); goal_weak = goal; wakeUp(goal); } return goal; } GoalPtr Worker::makeGoal(const DerivedPath & req, BuildMode buildMode) { return std::visit(overloaded { [&](const DerivedPath::Built & bfd) -> GoalPtr { if (auto bop = std::get_if<DerivedPath::Opaque>(&*bfd.drvPath)) return makeDerivationGoal(bop->path, bfd.outputs, buildMode); else throw UnimplementedError("Building dynamic derivations in one shot is not yet implemented."); }, [&](const DerivedPath::Opaque & bo) -> GoalPtr { return makePathSubstitutionGoal(bo.path, buildMode == bmRepair ? Repair : NoRepair); }, }, req.raw()); } template<typename K, typename G> static void removeGoal(std::shared_ptr<G> goal, std::map<K, std::weak_ptr<G>> & goalMap) { /* !!! inefficient */ for (auto i = goalMap.begin(); i != goalMap.end(); ) if (i->second.lock() == goal) { auto j = i; ++j; goalMap.erase(i); i = j; } else ++i; } void Worker::removeGoal(GoalPtr goal) { if (auto drvGoal = std::dynamic_pointer_cast<DerivationGoal>(goal)) nix::removeGoal(drvGoal, derivationGoals); else if (auto subGoal = std::dynamic_pointer_cast<PathSubstitutionGoal>(goal)) nix::removeGoal(subGoal, substitutionGoals); else if (auto subGoal = std::dynamic_pointer_cast<DrvOutputSubstitutionGoal>(goal)) nix::removeGoal(subGoal, drvOutputSubstitutionGoals); else assert(false); if (topGoals.find(goal) != topGoals.end()) { topGoals.erase(goal); /* If a top-level goal failed, then kill all other goals (unless keepGoing was set). */ if (goal->exitCode == Goal::ecFailed && !settings.keepGoing) topGoals.clear(); } /* Wake up goals waiting for any goal to finish. */ for (auto & i : waitingForAnyGoal) { GoalPtr goal = i.lock(); if (goal) wakeUp(goal); } waitingForAnyGoal.clear(); } void Worker::wakeUp(GoalPtr goal) { goal->trace("woken up"); addToWeakGoals(awake, goal); } size_t Worker::getNrLocalBuilds() { return nrLocalBuilds; } size_t Worker::getNrSubstitutions() { return nrSubstitutions; } void Worker::childStarted(GoalPtr goal, const std::set<MuxablePipePollState::CommChannel> & channels, bool inBuildSlot, bool respectTimeouts) { Child child; child.goal = goal; child.goal2 = goal.get(); child.channels = channels; child.timeStarted = child.lastOutput = steady_time_point::clock::now(); child.inBuildSlot = inBuildSlot; child.respectTimeouts = respectTimeouts; children.emplace_back(child); if (inBuildSlot) { switch (goal->jobCategory()) { case JobCategory::Substitution: nrSubstitutions++; break; case JobCategory::Build: nrLocalBuilds++; break; default: unreachable(); } } } void Worker::childTerminated(Goal * goal, bool wakeSleepers) { auto i = std::find_if(children.begin(), children.end(), [&](const Child & child) { return child.goal2 == goal; }); if (i == children.end()) return; if (i->inBuildSlot) { switch (goal->jobCategory()) { case JobCategory::Substitution: assert(nrSubstitutions > 0); nrSubstitutions--; break; case JobCategory::Build: assert(nrLocalBuilds > 0); nrLocalBuilds--; break; default: unreachable(); } } children.erase(i); if (wakeSleepers) { /* Wake up goals waiting for a build slot. */ for (auto & j : wantingToBuild) { GoalPtr goal = j.lock(); if (goal) wakeUp(goal); } wantingToBuild.clear(); } } void Worker::waitForBuildSlot(GoalPtr goal) { goal->trace("wait for build slot"); bool isSubstitutionGoal = goal->jobCategory() == JobCategory::Substitution; if ((!isSubstitutionGoal && getNrLocalBuilds() < settings.maxBuildJobs) || (isSubstitutionGoal && getNrSubstitutions() < settings.maxSubstitutionJobs)) wakeUp(goal); /* we can do it right away */ else addToWeakGoals(wantingToBuild, goal); } void Worker::waitForAnyGoal(GoalPtr goal) { debug("wait for any goal"); addToWeakGoals(waitingForAnyGoal, goal); } void Worker::waitForAWhile(GoalPtr goal) { debug("wait for a while"); addToWeakGoals(waitingForAWhile, goal); } void Worker::run(const Goals & _topGoals) { std::vector<nix::DerivedPath> topPaths; for (auto & i : _topGoals) { topGoals.insert(i); if (auto goal = dynamic_cast<DerivationGoal *>(i.get())) { topPaths.push_back(DerivedPath::Built { .drvPath = makeConstantStorePathRef(goal->drvPath), .outputs = goal->wantedOutputs, }); } else if (auto goal = dynamic_cast<PathSubstitutionGoal *>(i.get())) { topPaths.push_back(DerivedPath::Opaque{goal->storePath}); } } /* Call queryMissing() to efficiently query substitutes. */ StorePathSet willBuild, willSubstitute, unknown; uint64_t downloadSize, narSize; store.queryMissing(topPaths, willBuild, willSubstitute, unknown, downloadSize, narSize); debug("entered goal loop"); while (1) { checkInterrupt(); // TODO GC interface? if (auto localStore = dynamic_cast<LocalStore *>(&store)) localStore->autoGC(false); /* Call every wake goal (in the ordering established by CompareGoalPtrs). */ while (!awake.empty() && !topGoals.empty()) { Goals awake2; for (auto & i : awake) { GoalPtr goal = i.lock(); if (goal) awake2.insert(goal); } awake.clear(); for (auto & goal : awake2) { checkInterrupt(); goal->work(); if (topGoals.empty()) break; // stuff may have been cancelled } } if (topGoals.empty()) break; /* Wait for input. */ if (!children.empty() || !waitingForAWhile.empty()) waitForInput(); else if (awake.empty() && 0U == settings.maxBuildJobs) { if (getMachines().empty()) throw Error( R"( Unable to start any build; either increase '--max-jobs' or enable remote builds. For more information run 'man nix.conf' and search for '/machines'. )" ); else throw Error( R"( Unable to start any build; remote machines may not have all required system features. For more information run 'man nix.conf' and search for '/machines'. )" ); } else assert(!awake.empty()); } /* If --keep-going is not set, it's possible that the main goal exited while some of its subgoals were still active. But if --keep-going *is* set, then they must all be finished now. */ assert(!settings.keepGoing || awake.empty()); assert(!settings.keepGoing || wantingToBuild.empty()); assert(!settings.keepGoing || children.empty()); } void Worker::waitForInput() { printMsg(lvlVomit, "waiting for children"); /* Process output from the file descriptors attached to the children, namely log output and output path creation commands. We also use this to detect child termination: if we get EOF on the logger pipe of a build, we assume that the builder has terminated. */ bool useTimeout = false; long timeout = 0; auto before = steady_time_point::clock::now(); /* If we're monitoring for silence on stdout/stderr, or if there is a build timeout, then wait for input until the first deadline for any child. */ auto nearest = steady_time_point::max(); // nearest deadline if (settings.minFree.get() != 0) // Periodicallty wake up to see if we need to run the garbage collector. nearest = before + std::chrono::seconds(10); for (auto & i : children) { if (!i.respectTimeouts) continue; if (0 != settings.maxSilentTime) nearest = std::min(nearest, i.lastOutput + std::chrono::seconds(settings.maxSilentTime)); if (0 != settings.buildTimeout) nearest = std::min(nearest, i.timeStarted + std::chrono::seconds(settings.buildTimeout)); } if (nearest != steady_time_point::max()) { timeout = std::max(1L, (long) std::chrono::duration_cast<std::chrono::seconds>(nearest - before).count()); useTimeout = true; } /* If we are polling goals that are waiting for a lock, then wake up after a few seconds at most. */ if (!waitingForAWhile.empty()) { useTimeout = true; if (lastWokenUp == steady_time_point::min() || lastWokenUp > before) lastWokenUp = before; timeout = std::max(1L, (long) std::chrono::duration_cast<std::chrono::seconds>( lastWokenUp + std::chrono::seconds(settings.pollInterval) - before).count()); } else lastWokenUp = steady_time_point::min(); if (useTimeout) vomit("sleeping %d seconds", timeout); MuxablePipePollState state; #ifndef _WIN32 /* Use select() to wait for the input side of any logger pipe to become `available'. Note that `available' (i.e., non-blocking) includes EOF. */ for (auto & i : children) { for (auto & j : i.channels) { state.pollStatus.push_back((struct pollfd) { .fd = j, .events = POLLIN }); state.fdToPollStatus[j] = state.pollStatus.size() - 1; } } #endif state.poll( #ifdef _WIN32 ioport.get(), #endif useTimeout ? (std::optional { timeout * 1000 }) : std::nullopt); auto after = steady_time_point::clock::now(); /* Process all available file descriptors. FIXME: this is O(children * fds). */ decltype(children)::iterator i; for (auto j = children.begin(); j != children.end(); j = i) { i = std::next(j); checkInterrupt(); GoalPtr goal = j->goal.lock(); assert(goal); state.iterate( j->channels, [&](Descriptor k, std::string_view data) { printMsg(lvlVomit, "%1%: read %2% bytes", goal->getName(), data.size()); j->lastOutput = after; goal->handleChildOutput(k, data); }, [&](Descriptor k) { debug("%1%: got EOF", goal->getName()); goal->handleEOF(k); }); if (goal->exitCode == Goal::ecBusy && 0 != settings.maxSilentTime && j->respectTimeouts && after - j->lastOutput >= std::chrono::seconds(settings.maxSilentTime)) { goal->timedOut(Error( "%1% timed out after %2% seconds of silence", goal->getName(), settings.maxSilentTime)); } else if (goal->exitCode == Goal::ecBusy && 0 != settings.buildTimeout && j->respectTimeouts && after - j->timeStarted >= std::chrono::seconds(settings.buildTimeout)) { goal->timedOut(Error( "%1% timed out after %2% seconds", goal->getName(), settings.buildTimeout)); } } if (!waitingForAWhile.empty() && lastWokenUp + std::chrono::seconds(settings.pollInterval) <= after) { lastWokenUp = after; for (auto & i : waitingForAWhile) { GoalPtr goal = i.lock(); if (goal) wakeUp(goal); } waitingForAWhile.clear(); } } unsigned int Worker::failingExitStatus() { // See API docs in header for explanation unsigned int mask = 0; bool buildFailure = permanentFailure || timedOut || hashMismatch; if (buildFailure) mask |= 0x04; // 100 if (timedOut) mask |= 0x01; // 101 if (hashMismatch) mask |= 0x02; // 102 if (checkMismatch) { mask |= 0x08; // 104 } if (mask) mask |= 0x60; return mask ? mask : 1; } bool Worker::pathContentsGood(const StorePath & path) { auto i = pathContentsGoodCache.find(path); if (i != pathContentsGoodCache.end()) return i->second; printInfo("checking path '%s'...", store.printStorePath(path)); auto info = store.queryPathInfo(path); bool res; if (!pathExists(store.printStorePath(path))) res = false; else { auto current = hashPath( {store.getFSAccessor(), CanonPath(store.printStorePath(path))}, FileIngestionMethod::NixArchive, info->narHash.algo).first; Hash nullHash(HashAlgorithm::SHA256); res = info->narHash == nullHash || info->narHash == current; } pathContentsGoodCache.insert_or_assign(path, res); if (!res) printError("path '%s' is corrupted or missing!", store.printStorePath(path)); return res; } void Worker::markContentsGood(const StorePath & path) { pathContentsGoodCache.insert_or_assign(path, true); } GoalPtr upcast_goal(std::shared_ptr<PathSubstitutionGoal> subGoal) { return subGoal; } GoalPtr upcast_goal(std::shared_ptr<DrvOutputSubstitutionGoal> subGoal) { return subGoal; } }
17,361
C++
.cc
468
29.641026
154
0.622218
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
10,858
goal.cc
NixOS_nix/src/libstore/build/goal.cc
#include "goal.hh" #include "worker.hh" namespace nix { using Co = nix::Goal::Co; using promise_type = nix::Goal::promise_type; using handle_type = nix::Goal::handle_type; using Suspend = nix::Goal::Suspend; Co::Co(Co&& rhs) { this->handle = rhs.handle; rhs.handle = nullptr; } void Co::operator=(Co&& rhs) { this->handle = rhs.handle; rhs.handle = nullptr; } Co::~Co() { if (handle) { handle.promise().alive = false; handle.destroy(); } } Co promise_type::get_return_object() { auto handle = handle_type::from_promise(*this); return Co{handle}; }; std::coroutine_handle<> promise_type::final_awaiter::await_suspend(handle_type h) noexcept { auto& p = h.promise(); auto goal = p.goal; assert(goal); goal->trace("in final_awaiter"); auto c = std::move(p.continuation); if (c) { // We still have a continuation, i.e. work to do. // We assert that the goal is still busy. assert(goal->exitCode == ecBusy); assert(goal->top_co); // Goal must have an active coroutine. assert(goal->top_co->handle == h); // The active coroutine must be us. assert(p.alive); // We must not have been destructed. // we move continuation to the top, // note: previous top_co is actually h, so by moving into it, // we're calling the destructor on h, DON'T use h and p after this! // We move our continuation into `top_co`, i.e. the marker for the active continuation. // By doing this we destruct the old `top_co`, i.e. us, so `h` can't be used anymore. // Be careful not to access freed memory! goal->top_co = std::move(c); // We resume `top_co`. return goal->top_co->handle; } else { // We have no continuation, i.e. no more work to do, // so the goal must not be busy anymore. assert(goal->exitCode != ecBusy); // We reset `top_co` for good measure. p.goal->top_co = {}; // We jump to the noop coroutine, which doesn't do anything and immediately suspends. // This passes control back to the caller of goal.work(). return std::noop_coroutine(); } } void promise_type::return_value(Co&& next) { goal->trace("return_value(Co&&)"); // Save old continuation. auto old_continuation = std::move(continuation); // We set next as our continuation. continuation = std::move(next); // We set next's goal, and thus it must not have one already. assert(!continuation->handle.promise().goal); continuation->handle.promise().goal = goal; // Nor can next have a continuation, as we set it to our old one. assert(!continuation->handle.promise().continuation); continuation->handle.promise().continuation = std::move(old_continuation); } std::coroutine_handle<> nix::Goal::Co::await_suspend(handle_type caller) { assert(handle); // we must be a valid coroutine auto& p = handle.promise(); assert(!p.continuation); // we must have no continuation assert(!p.goal); // we must not have a goal yet auto goal = caller.promise().goal; assert(goal); p.goal = goal; p.continuation = std::move(goal->top_co); // we set our continuation to be top_co (i.e. caller) goal->top_co = std::move(*this); // we set top_co to ourselves, don't use this anymore after this! return p.goal->top_co->handle; // we execute ourselves } bool CompareGoalPtrs::operator() (const GoalPtr & a, const GoalPtr & b) const { std::string s1 = a->key(); std::string s2 = b->key(); return s1 < s2; } BuildResult Goal::getBuildResult(const DerivedPath & req) const { BuildResult res { buildResult }; if (auto pbp = std::get_if<DerivedPath::Built>(&req)) { auto & bp = *pbp; /* Because goals are in general shared between derived paths that share the same derivation, we need to filter their results to get back just the results we care about. */ for (auto it = res.builtOutputs.begin(); it != res.builtOutputs.end();) { if (bp.outputs.contains(it->first)) ++it; else it = res.builtOutputs.erase(it); } } return res; } void addToWeakGoals(WeakGoals & goals, GoalPtr p) { if (goals.find(p) != goals.end()) return; goals.insert(p); } void Goal::addWaitee(GoalPtr waitee) { waitees.insert(waitee); addToWeakGoals(waitee->waiters, shared_from_this()); } void Goal::waiteeDone(GoalPtr waitee, ExitCode result) { assert(waitees.count(waitee)); waitees.erase(waitee); trace(fmt("waitee '%s' done; %d left", waitee->name, waitees.size())); if (result == ecFailed || result == ecNoSubstituters || result == ecIncompleteClosure) ++nrFailed; if (result == ecNoSubstituters) ++nrNoSubstituters; if (result == ecIncompleteClosure) ++nrIncompleteClosure; if (waitees.empty() || (result == ecFailed && !settings.keepGoing)) { /* If we failed and keepGoing is not set, we remove all remaining waitees. */ for (auto & goal : waitees) { goal->waiters.extract(shared_from_this()); } waitees.clear(); worker.wakeUp(shared_from_this()); } } Goal::Done Goal::amDone(ExitCode result, std::optional<Error> ex) { trace("done"); assert(top_co); assert(exitCode == ecBusy); assert(result == ecSuccess || result == ecFailed || result == ecNoSubstituters || result == ecIncompleteClosure); exitCode = result; if (ex) { if (!waiters.empty()) logError(ex->info()); else this->ex = std::move(*ex); } for (auto & i : waiters) { GoalPtr goal = i.lock(); if (goal) goal->waiteeDone(shared_from_this(), result); } waiters.clear(); worker.removeGoal(shared_from_this()); cleanup(); // We drop the continuation. // In `final_awaiter` this will signal that there is no more work to be done. top_co->handle.promise().continuation = {}; // won't return to caller because of logic in final_awaiter return Done{}; } void Goal::trace(std::string_view s) { debug("%1%: %2%", name, s); } void Goal::work() { assert(top_co); assert(top_co->handle); assert(top_co->handle.promise().alive); top_co->handle.resume(); // We either should be in a state where we can be work()-ed again, // or we should be done. assert(top_co || exitCode != ecBusy); } }
6,536
C++
.cc
175
31.697143
117
0.633687
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,859
nix_api_store.cc
NixOS_nix/src/libstore-c/nix_api_store.cc
#include "nix_api_store.h" #include "nix_api_store_internal.h" #include "nix_api_util.h" #include "nix_api_util_internal.h" #include "path.hh" #include "store-api.hh" #include "build-result.hh" #include "globals.hh" nix_err nix_libstore_init(nix_c_context * context) { if (context) context->last_err_code = NIX_OK; try { nix::initLibStore(); } NIXC_CATCH_ERRS } nix_err nix_libstore_init_no_load_config(nix_c_context * context) { if (context) context->last_err_code = NIX_OK; try { nix::initLibStore(false); } NIXC_CATCH_ERRS } Store * nix_store_open(nix_c_context * context, const char * uri, const char *** params) { if (context) context->last_err_code = NIX_OK; try { std::string uri_str = uri ? uri : ""; if (uri_str.empty()) return new Store{nix::openStore()}; if (!params) return new Store{nix::openStore(uri_str)}; nix::Store::Params params_map; for (size_t i = 0; params[i] != nullptr; i++) { params_map[params[i][0]] = params[i][1]; } return new Store{nix::openStore(uri_str, params_map)}; } NIXC_CATCH_ERRS_NULL } void nix_store_free(Store * store) { delete store; } nix_err nix_store_get_uri(nix_c_context * context, Store * store, nix_get_string_callback callback, void * user_data) { if (context) context->last_err_code = NIX_OK; try { auto res = store->ptr->getUri(); return call_nix_get_string_callback(res, callback, user_data); } NIXC_CATCH_ERRS } nix_err nix_store_get_version(nix_c_context * context, Store * store, nix_get_string_callback callback, void * user_data) { if (context) context->last_err_code = NIX_OK; try { auto res = store->ptr->getVersion(); return call_nix_get_string_callback(res.value_or(""), callback, user_data); } NIXC_CATCH_ERRS } bool nix_store_is_valid_path(nix_c_context * context, Store * store, StorePath * path) { if (context) context->last_err_code = NIX_OK; try { return store->ptr->isValidPath(path->path); } NIXC_CATCH_ERRS_RES(false); } StorePath * nix_store_parse_path(nix_c_context * context, Store * store, const char * path) { if (context) context->last_err_code = NIX_OK; try { nix::StorePath s = store->ptr->parseStorePath(path); return new StorePath{std::move(s)}; } NIXC_CATCH_ERRS_NULL } nix_err nix_store_realise( nix_c_context * context, Store * store, StorePath * path, void * userdata, void (*callback)(void * userdata, const char *, const char *)) { if (context) context->last_err_code = NIX_OK; try { const std::vector<nix::DerivedPath> paths{nix::DerivedPath::Built{ .drvPath = nix::makeConstantStorePathRef(path->path), .outputs = nix::OutputsSpec::All{}}}; const auto nixStore = store->ptr; auto results = nixStore->buildPathsWithResults(paths, nix::bmNormal, nixStore); if (callback) { for (const auto & result : results) { for (const auto & [outputName, realisation] : result.builtOutputs) { auto op = store->ptr->printStorePath(realisation.outPath); callback(userdata, outputName.c_str(), op.c_str()); } } } } NIXC_CATCH_ERRS } void nix_store_path_name(const StorePath * store_path, nix_get_string_callback callback, void * user_data) { std::string_view name = store_path->path.name(); callback(name.data(), name.size(), user_data); } void nix_store_path_free(StorePath * sp) { delete sp; } StorePath * nix_store_path_clone(const StorePath * p) { return new StorePath{p->path}; } nix_err nix_store_copy_closure(nix_c_context * context, Store * srcStore, Store * dstStore, StorePath * path) { if (context) context->last_err_code = NIX_OK; try { nix::RealisedPath::Set paths; paths.insert(path->path); nix::copyClosure(*srcStore->ptr, *dstStore->ptr, paths); } NIXC_CATCH_ERRS }
4,165
C++
.cc
137
24.927007
117
0.626404
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,860
build-remote.cc
NixOS_nix/src/build-remote/build-remote.cc
#include <cstdlib> #include <cstring> #include <algorithm> #include <set> #include <memory> #include <tuple> #include <iomanip> #if __APPLE__ #include <sys/time.h> #endif #include "machines.hh" #include "shared.hh" #include "plugin.hh" #include "pathlocks.hh" #include "globals.hh" #include "serialise.hh" #include "build-result.hh" #include "store-api.hh" #include "strings.hh" #include "derivations.hh" #include "local-store.hh" #include "legacy.hh" #include "experimental-features.hh" using namespace nix; using std::cin; static void handleAlarm(int sig) { } std::string escapeUri(std::string uri) { std::replace(uri.begin(), uri.end(), '/', '_'); return uri; } static std::string currentLoad; static AutoCloseFD openSlotLock(const Machine & m, uint64_t slot) { return openLockFile(fmt("%s/%s-%d", currentLoad, escapeUri(m.storeUri.render()), slot), true); } static bool allSupportedLocally(Store & store, const std::set<std::string>& requiredFeatures) { for (auto & feature : requiredFeatures) if (!store.systemFeatures.get().count(feature)) return false; return true; } static int main_build_remote(int argc, char * * argv) { { logger = makeJSONLogger(*logger); /* Ensure we don't get any SSH passphrase or host key popups. */ unsetenv("DISPLAY"); unsetenv("SSH_ASKPASS"); /* If we ever use the common args framework, make sure to remove initPlugins below and initialize settings first. */ if (argc != 2) throw UsageError("called without required arguments"); verbosity = (Verbosity) std::stoll(argv[1]); FdSource source(STDIN_FILENO); /* Read the parent's settings. */ while (readInt(source)) { auto name = readString(source); auto value = readString(source); settings.set(name, value); } auto maxBuildJobs = settings.maxBuildJobs; settings.maxBuildJobs.set("1"); // hack to make tests with local?root= work initPlugins(); auto store = openStore(); /* It would be more appropriate to use $XDG_RUNTIME_DIR, since that gets cleared on reboot, but it wouldn't work on macOS. */ auto currentLoadName = "/current-load"; if (auto localStore = store.dynamic_pointer_cast<LocalFSStore>()) currentLoad = std::string { localStore->stateDir } + currentLoadName; else currentLoad = settings.nixStateDir + currentLoadName; std::shared_ptr<Store> sshStore; AutoCloseFD bestSlotLock; auto machines = getMachines(); debug("got %d remote builders", machines.size()); if (machines.empty()) { std::cerr << "# decline-permanently\n"; return 0; } std::optional<StorePath> drvPath; std::string storeUri; while (true) { try { auto s = readString(source); if (s != "try") return 0; } catch (EndOfFile &) { return 0; } auto amWilling = readInt(source); auto neededSystem = readString(source); drvPath = store->parseStorePath(readString(source)); auto requiredFeatures = readStrings<std::set<std::string>>(source); /* It would be possible to build locally after some builds clear out, so don't show the warning now: */ bool couldBuildLocally = maxBuildJobs > 0 && ( neededSystem == settings.thisSystem || settings.extraPlatforms.get().count(neededSystem) > 0) && allSupportedLocally(*store, requiredFeatures); /* It's possible to build this locally right now: */ bool canBuildLocally = amWilling && couldBuildLocally; /* Error ignored here, will be caught later */ mkdir(currentLoad.c_str(), 0777); while (true) { bestSlotLock = -1; AutoCloseFD lock = openLockFile(currentLoad + "/main-lock", true); lockFile(lock.get(), ltWrite, true); bool rightType = false; Machine * bestMachine = nullptr; uint64_t bestLoad = 0; for (auto & m : machines) { debug("considering building on remote machine '%s'", m.storeUri.render()); if (m.enabled && m.systemSupported(neededSystem) && m.allSupported(requiredFeatures) && m.mandatoryMet(requiredFeatures)) { rightType = true; AutoCloseFD free; uint64_t load = 0; for (uint64_t slot = 0; slot < m.maxJobs; ++slot) { auto slotLock = openSlotLock(m, slot); if (lockFile(slotLock.get(), ltWrite, false)) { if (!free) { free = std::move(slotLock); } } else { ++load; } } if (!free) { continue; } bool best = false; if (!bestSlotLock) { best = true; } else if (load / m.speedFactor < bestLoad / bestMachine->speedFactor) { best = true; } else if (load / m.speedFactor == bestLoad / bestMachine->speedFactor) { if (m.speedFactor > bestMachine->speedFactor) { best = true; } else if (m.speedFactor == bestMachine->speedFactor) { if (load < bestLoad) { best = true; } } } if (best) { bestLoad = load; bestSlotLock = std::move(free); bestMachine = &m; } } } if (!bestSlotLock) { if (rightType && !canBuildLocally) std::cerr << "# postpone\n"; else { // build the hint template. std::string errorText = "Failed to find a machine for remote build!\n" "derivation: %s\nrequired (system, features): (%s, [%s])"; errorText += "\n%s available machines:"; errorText += "\n(systems, maxjobs, supportedFeatures, mandatoryFeatures)"; for (unsigned int i = 0; i < machines.size(); ++i) errorText += "\n([%s], %s, [%s], [%s])"; // add the template values. std::string drvstr; if (drvPath.has_value()) drvstr = drvPath->to_string(); else drvstr = "<unknown>"; auto error = HintFmt::fromFormatString(errorText); error % drvstr % neededSystem % concatStringsSep<StringSet>(", ", requiredFeatures) % machines.size(); for (auto & m : machines) error % concatStringsSep<StringSet>(", ", m.systemTypes) % m.maxJobs % concatStringsSep<StringSet>(", ", m.supportedFeatures) % concatStringsSep<StringSet>(", ", m.mandatoryFeatures); printMsg(couldBuildLocally ? lvlChatty : lvlWarn, error.str()); std::cerr << "# decline\n"; } break; } #if __APPLE__ futimes(bestSlotLock.get(), NULL); #else futimens(bestSlotLock.get(), NULL); #endif lock = -1; try { storeUri = bestMachine->storeUri.render(); Activity act(*logger, lvlTalkative, actUnknown, fmt("connecting to '%s'", storeUri)); sshStore = bestMachine->openStore(); sshStore->connect(); } catch (std::exception & e) { auto msg = chomp(drainFD(5, false)); printError("cannot build on '%s': %s%s", storeUri, e.what(), msg.empty() ? "" : ": " + msg); bestMachine->enabled = false; continue; } goto connected; } } connected: close(5); assert(sshStore); std::cerr << "# accept\n" << storeUri << "\n"; auto inputs = readStrings<PathSet>(source); auto wantedOutputs = readStrings<StringSet>(source); AutoCloseFD uploadLock; { auto setUpdateLock = [&](auto && fileName){ uploadLock = openLockFile(currentLoad + "/" + escapeUri(fileName) + ".upload-lock", true); }; try { setUpdateLock(storeUri); } catch (SysError & e) { if (e.errNo != ENAMETOOLONG) throw; // Try again hashing the store URL so we have a shorter path auto h = hashString(HashAlgorithm::MD5, storeUri); setUpdateLock(h.to_string(HashFormat::Base64, false)); } } { Activity act(*logger, lvlTalkative, actUnknown, fmt("waiting for the upload lock to '%s'", storeUri)); auto old = signal(SIGALRM, handleAlarm); alarm(15 * 60); if (!lockFile(uploadLock.get(), ltWrite, true)) printError("somebody is hogging the upload lock for '%s', continuing..."); alarm(0); signal(SIGALRM, old); } auto substitute = settings.buildersUseSubstitutes ? Substitute : NoSubstitute; { Activity act(*logger, lvlTalkative, actUnknown, fmt("copying dependencies to '%s'", storeUri)); copyPaths(*store, *sshStore, store->parseStorePathSet(inputs), NoRepair, NoCheckSigs, substitute); } uploadLock = -1; auto drv = store->readDerivation(*drvPath); std::optional<BuildResult> optResult; // If we don't know whether we are trusted (e.g. `ssh://` // stores), we assume we are. This is necessary for backwards // compat. bool trustedOrLegacy = ({ std::optional trusted = sshStore->isTrustedClient(); !trusted || *trusted; }); // See the very large comment in `case WorkerProto::Op::BuildDerivation:` in // `src/libstore/daemon.cc` that explains the trust model here. // // This condition mirrors that: that code enforces the "rules" outlined there; // we do the best we can given those "rules". if (trustedOrLegacy || drv.type().isCA()) { // Hijack the inputs paths of the derivation to include all // the paths that come from the `inputDrvs` set. We don’t do // that for the derivations whose `inputDrvs` is empty // because: // // 1. It’s not needed // // 2. Changing the `inputSrcs` set changes the associated // output ids, which break CA derivations if (!drv.inputDrvs.map.empty()) drv.inputSrcs = store->parseStorePathSet(inputs); optResult = sshStore->buildDerivation(*drvPath, (const BasicDerivation &) drv); auto & result = *optResult; if (!result.success()) throw Error("build of '%s' on '%s' failed: %s", store->printStorePath(*drvPath), storeUri, result.errorMsg); } else { copyClosure(*store, *sshStore, StorePathSet {*drvPath}, NoRepair, NoCheckSigs, substitute); auto res = sshStore->buildPathsWithResults({ DerivedPath::Built { .drvPath = makeConstantStorePathRef(*drvPath), .outputs = OutputsSpec::All {}, } }); // One path to build should produce exactly one build result assert(res.size() == 1); optResult = std::move(res[0]); } auto outputHashes = staticOutputHashes(*store, drv); std::set<Realisation> missingRealisations; StorePathSet missingPaths; if (experimentalFeatureSettings.isEnabled(Xp::CaDerivations) && !drv.type().hasKnownOutputPaths()) { for (auto & outputName : wantedOutputs) { auto thisOutputHash = outputHashes.at(outputName); auto thisOutputId = DrvOutput{ thisOutputHash, outputName }; if (!store->queryRealisation(thisOutputId)) { debug("missing output %s", outputName); assert(optResult); auto & result = *optResult; auto i = result.builtOutputs.find(outputName); assert(i != result.builtOutputs.end()); auto & newRealisation = i->second; missingRealisations.insert(newRealisation); missingPaths.insert(newRealisation.outPath); } } } else { auto outputPaths = drv.outputsAndOptPaths(*store); for (auto & [outputName, hopefullyOutputPath] : outputPaths) { assert(hopefullyOutputPath.second); if (!store->isValidPath(*hopefullyOutputPath.second)) missingPaths.insert(*hopefullyOutputPath.second); } } if (!missingPaths.empty()) { Activity act(*logger, lvlTalkative, actUnknown, fmt("copying outputs from '%s'", storeUri)); if (auto localStore = store.dynamic_pointer_cast<LocalStore>()) for (auto & path : missingPaths) localStore->locksHeld.insert(store->printStorePath(path)); /* FIXME: ugly */ copyPaths(*sshStore, *store, missingPaths, NoRepair, NoCheckSigs, NoSubstitute); } // XXX: Should be done as part of `copyPaths` for (auto & realisation : missingRealisations) { // Should hold, because if the feature isn't enabled the set // of missing realisations should be empty experimentalFeatureSettings.require(Xp::CaDerivations); store->registerDrvOutput(realisation); } return 0; } } static RegisterLegacyCommand r_build_remote("build-remote", main_build_remote);
15,280
C++
.cc
332
31.162651
124
0.519621
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
10,861
context.cc
NixOS_nix/src/libexpr-test-support/tests/value/context.cc
#include <rapidcheck.h> #include "tests/path.hh" #include "tests/value/context.hh" namespace rc { using namespace nix; Gen<NixStringContextElem::DrvDeep> Arbitrary<NixStringContextElem::DrvDeep>::arbitrary() { return gen::just(NixStringContextElem::DrvDeep { .drvPath = *gen::arbitrary<StorePath>(), }); } Gen<NixStringContextElem> Arbitrary<NixStringContextElem>::arbitrary() { switch (*gen::inRange<uint8_t>(0, std::variant_size_v<NixStringContextElem::Raw>)) { case 0: return gen::just<NixStringContextElem>(*gen::arbitrary<NixStringContextElem::Opaque>()); case 1: return gen::just<NixStringContextElem>(*gen::arbitrary<NixStringContextElem::DrvDeep>()); case 2: return gen::just<NixStringContextElem>(*gen::arbitrary<NixStringContextElem::Built>()); default: assert(false); } } }
862
C++
.cc
25
30.4
97
0.722356
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,862
posix-source-accessor.cc
NixOS_nix/src/libutil/posix-source-accessor.cc
#include "posix-source-accessor.hh" #include "source-path.hh" #include "signals.hh" #include "sync.hh" #include <unordered_map> namespace nix { PosixSourceAccessor::PosixSourceAccessor(std::filesystem::path && argRoot) : root(std::move(argRoot)) { assert(root.empty() || root.is_absolute()); displayPrefix = root.string(); } PosixSourceAccessor::PosixSourceAccessor() : PosixSourceAccessor(std::filesystem::path {}) { } SourcePath PosixSourceAccessor::createAtRoot(const std::filesystem::path & path) { std::filesystem::path path2 = absPath(path); return { make_ref<PosixSourceAccessor>(path2.root_path()), CanonPath { path2.relative_path().string() }, }; } std::filesystem::path PosixSourceAccessor::makeAbsPath(const CanonPath & path) { return root.empty() ? (std::filesystem::path { path.abs() }) : path.isRoot() ? /* Don't append a slash for the root of the accessor, since it can be a non-directory (e.g. in the case of `fetchTree { type = "file" }`). */ root : root / path.rel(); } void PosixSourceAccessor::readFile( const CanonPath & path, Sink & sink, std::function<void(uint64_t)> sizeCallback) { assertNoSymlinks(path); auto ap = makeAbsPath(path); AutoCloseFD fd = toDescriptor(open(ap.string().c_str(), O_RDONLY #ifndef _WIN32 | O_NOFOLLOW | O_CLOEXEC #endif )); if (!fd) throw SysError("opening file '%1%'", ap.string()); struct stat st; if (fstat(fromDescriptorReadOnly(fd.get()), &st) == -1) throw SysError("statting file"); sizeCallback(st.st_size); off_t left = st.st_size; std::array<unsigned char, 64 * 1024> buf; while (left) { checkInterrupt(); ssize_t rd = read(fromDescriptorReadOnly(fd.get()), buf.data(), (size_t) std::min(left, (off_t) buf.size())); if (rd == -1) { if (errno != EINTR) throw SysError("reading from file '%s'", showPath(path)); } else if (rd == 0) throw SysError("unexpected end-of-file reading '%s'", showPath(path)); else { assert(rd <= left); sink({(char *) buf.data(), (size_t) rd}); left -= rd; } } } bool PosixSourceAccessor::pathExists(const CanonPath & path) { if (auto parent = path.parent()) assertNoSymlinks(*parent); return nix::pathExists(makeAbsPath(path).string()); } std::optional<struct stat> PosixSourceAccessor::cachedLstat(const CanonPath & path) { static SharedSync<std::unordered_map<Path, std::optional<struct stat>>> _cache; // Note: we convert std::filesystem::path to Path because the // former is not hashable on libc++. Path absPath = makeAbsPath(path).string(); { auto cache(_cache.readLock()); auto i = cache->find(absPath); if (i != cache->end()) return i->second; } auto st = nix::maybeLstat(absPath.c_str()); auto cache(_cache.lock()); if (cache->size() >= 16384) cache->clear(); cache->emplace(absPath, st); return st; } std::optional<SourceAccessor::Stat> PosixSourceAccessor::maybeLstat(const CanonPath & path) { if (auto parent = path.parent()) assertNoSymlinks(*parent); auto st = cachedLstat(path); if (!st) return std::nullopt; mtime = std::max(mtime, st->st_mtime); return Stat { .type = S_ISREG(st->st_mode) ? tRegular : S_ISDIR(st->st_mode) ? tDirectory : S_ISLNK(st->st_mode) ? tSymlink : tMisc, .fileSize = S_ISREG(st->st_mode) ? std::optional<uint64_t>(st->st_size) : std::nullopt, .isExecutable = S_ISREG(st->st_mode) && st->st_mode & S_IXUSR, }; } SourceAccessor::DirEntries PosixSourceAccessor::readDirectory(const CanonPath & path) { assertNoSymlinks(path); DirEntries res; try { for (auto & entry : std::filesystem::directory_iterator{makeAbsPath(path)}) { checkInterrupt(); auto type = [&]() -> std::optional<Type> { std::filesystem::file_type nativeType; try { nativeType = entry.symlink_status().type(); } catch (std::filesystem::filesystem_error & e) { // We cannot always stat the child. (Ideally there is no // stat because the native directory entry has the type // already, but this isn't always the case.) if (e.code() == std::errc::permission_denied || e.code() == std::errc::operation_not_permitted) return std::nullopt; else throw; } // cannot exhaustively enumerate because implementation-specific // additional file types are allowed. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wswitch-enum" switch (nativeType) { case std::filesystem::file_type::regular: return Type::tRegular; break; case std::filesystem::file_type::symlink: return Type::tSymlink; break; case std::filesystem::file_type::directory: return Type::tDirectory; break; default: return tMisc; } #pragma GCC diagnostic pop }(); res.emplace(entry.path().filename().string(), type); } } catch (std::filesystem::filesystem_error & e) { throw SysError("reading directory %1%", showPath(path)); } return res; } std::string PosixSourceAccessor::readLink(const CanonPath & path) { if (auto parent = path.parent()) assertNoSymlinks(*parent); return nix::readLink(makeAbsPath(path).string()); } std::optional<std::filesystem::path> PosixSourceAccessor::getPhysicalPath(const CanonPath & path) { return makeAbsPath(path); } void PosixSourceAccessor::assertNoSymlinks(CanonPath path) { while (!path.isRoot()) { auto st = cachedLstat(path); if (st && S_ISLNK(st->st_mode)) throw Error("path '%s' is a symlink", showPath(path)); path.pop(); } } ref<SourceAccessor> getFSSourceAccessor() { static auto rootFS = make_ref<PosixSourceAccessor>(); return rootFS; } ref<SourceAccessor> makeFSSourceAccessor(std::filesystem::path root) { return make_ref<PosixSourceAccessor>(std::move(root)); } }
6,386
C++
.cc
174
29.83908
117
0.622251
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,863
experimental-features.cc
NixOS_nix/src/libutil/experimental-features.cc
#include "experimental-features.hh" #include "fmt.hh" #include "util.hh" #include "nlohmann/json.hpp" namespace nix { struct ExperimentalFeatureDetails { ExperimentalFeature tag; std::string_view name; std::string_view description; std::string_view trackingUrl; }; /** * If two different PRs both add an experimental feature, and we just * used a number for this, we *woudln't* get merge conflict and the * counter will be incremented once instead of twice, causing a build * failure. * * By instead defining this instead as 1 + the bottom experimental * feature, we either have no issue at all if few features are not added * at the end of the list, or a proper merge conflict if they are. */ constexpr size_t numXpFeatures = 1 + static_cast<size_t>(Xp::PipeOperators); constexpr std::array<ExperimentalFeatureDetails, numXpFeatures> xpFeatureDetails = {{ { .tag = Xp::CaDerivations, .name = "ca-derivations", .description = R"( Allow derivations to be content-addressed in order to prevent rebuilds when changes to the derivation do not result in changes to the derivation's output. See [__contentAddressed](@docroot@/language/advanced-attributes.md#adv-attr-__contentAddressed) for details. )", .trackingUrl = "https://github.com/NixOS/nix/milestone/35", }, { .tag = Xp::ImpureDerivations, .name = "impure-derivations", .description = R"( Allow derivations to produce non-fixed outputs by setting the `__impure` derivation attribute to `true`. An impure derivation can have differing outputs each time it is built. Example: ``` derivation { name = "impure"; builder = /bin/sh; __impure = true; # mark this derivation as impure args = [ "-c" "read -n 10 random < /dev/random; echo $random > $out" ]; system = builtins.currentSystem; } ``` Each time this derivation is built, it can produce a different output (as the builder outputs random bytes to `$out`). Impure derivations also have access to the network, and only fixed-output or other impure derivations can rely on impure derivations. Finally, an impure derivation cannot also be [content-addressed](#xp-feature-ca-derivations). This is a more explicit alternative to using [`builtins.currentTime`](@docroot@/language/builtins.md#builtins-currentTime). )", .trackingUrl = "https://github.com/NixOS/nix/milestone/42", }, { .tag = Xp::Flakes, .name = "flakes", .description = R"( Enable flakes. See the manual entry for [`nix flake`](@docroot@/command-ref/new-cli/nix3-flake.md) for details. )", .trackingUrl = "https://github.com/NixOS/nix/milestone/27", }, { .tag = Xp::FetchTree, .name = "fetch-tree", .description = R"( Enable the use of the [`fetchTree`](@docroot@/language/builtins.md#builtins-fetchTree) built-in function in the Nix language. `fetchTree` exposes a generic interface for fetching remote file system trees from different types of remote sources. The [`flakes`](#xp-feature-flakes) feature flag always enables `fetch-tree`. This built-in was previously guarded by the `flakes` experimental feature because of that overlap. Enabling just this feature serves as a "release candidate", allowing users to try it out in isolation. )", .trackingUrl = "https://github.com/NixOS/nix/milestone/31", }, { .tag = Xp::NixCommand, .name = "nix-command", .description = R"( Enable the new `nix` subcommands. See the manual on [`nix`](@docroot@/command-ref/new-cli/nix.md) for details. )", .trackingUrl = "https://github.com/NixOS/nix/milestone/28", }, { .tag = Xp::GitHashing, .name = "git-hashing", .description = R"( Allow creating (content-addressed) store objects which are hashed via Git's hashing algorithm. These store objects will not be understandable by older versions of Nix. )", .trackingUrl = "https://github.com/NixOS/nix/milestone/41", }, { .tag = Xp::RecursiveNix, .name = "recursive-nix", .description = R"( Allow derivation builders to call Nix, and thus build derivations recursively. Example: ``` with import <nixpkgs> {}; runCommand "foo" { buildInputs = [ nix jq ]; NIX_PATH = "nixpkgs=${<nixpkgs>}"; } '' hello=$(nix-build -E '(import <nixpkgs> {}).hello.overrideDerivation (args: { name = "recursive-hello"; })') mkdir -p $out/bin ln -s $hello/bin/hello $out/bin/hello '' ``` An important restriction on recursive builders is disallowing arbitrary substitutions. For example, running ``` nix-store -r /nix/store/kmwd1hq55akdb9sc7l3finr175dajlby-hello-2.10 ``` in the above `runCommand` script would be disallowed, as this could lead to derivations with hidden dependencies or breaking reproducibility by relying on the current state of the Nix store. An exception would be if `/nix/store/kmwd1hq55akdb9sc7l3finr175dajlby-hello-2.10` were already in the build inputs or built by a previous recursive Nix call. )", .trackingUrl = "https://github.com/NixOS/nix/milestone/47", }, { .tag = Xp::NoUrlLiterals, .name = "no-url-literals", .description = R"( Disallow unquoted URLs as part of the Nix language syntax. The Nix language allows for URL literals, like so: ``` $ nix repl Welcome to Nix 2.15.0. Type :? for help. nix-repl> http://foo "http://foo" ``` But enabling this experimental feature will cause the Nix parser to throw an error when encountering a URL literal: ``` $ nix repl --extra-experimental-features 'no-url-literals' Welcome to Nix 2.15.0. Type :? for help. nix-repl> http://foo error: URL literals are disabled at «string»:1:1: 1| http://foo | ^ ``` While this is currently an experimental feature, unquoted URLs are being deprecated and their usage is discouraged. The reason is that, as opposed to path literals, URLs have no special properties that distinguish them from regular strings, URLs containing parameters have to be quoted anyway, and unquoted URLs may confuse external tooling. )", .trackingUrl = "https://github.com/NixOS/nix/milestone/44", }, { .tag = Xp::FetchClosure, .name = "fetch-closure", .description = R"( Enable the use of the [`fetchClosure`](@docroot@/language/builtins.md#builtins-fetchClosure) built-in function in the Nix language. )", .trackingUrl = "https://github.com/NixOS/nix/milestone/40", }, { .tag = Xp::AutoAllocateUids, .name = "auto-allocate-uids", .description = R"( Allows Nix to automatically pick UIDs for builds, rather than creating `nixbld*` user accounts. See the [`auto-allocate-uids`](@docroot@/command-ref/conf-file.md#conf-auto-allocate-uids) setting for details. )", .trackingUrl = "https://github.com/NixOS/nix/milestone/34", }, { .tag = Xp::Cgroups, .name = "cgroups", .description = R"( Allows Nix to execute builds inside cgroups. See the [`use-cgroups`](@docroot@/command-ref/conf-file.md#conf-use-cgroups) setting for details. )", .trackingUrl = "https://github.com/NixOS/nix/milestone/36", }, { .tag = Xp::DaemonTrustOverride, .name = "daemon-trust-override", .description = R"( Allow forcing trusting or not trusting clients with `nix-daemon`. This is useful for testing, but possibly also useful for various experiments with `nix-daemon --stdio` networking. )", .trackingUrl = "https://github.com/NixOS/nix/milestone/38", }, { .tag = Xp::DynamicDerivations, .name = "dynamic-derivations", .description = R"( Allow the use of a few things related to dynamic derivations: - "text hashing" derivation outputs, so we can build .drv files. - dependencies in derivations on the outputs of derivations that are themselves derivations outputs. )", .trackingUrl = "https://github.com/NixOS/nix/milestone/39", }, { .tag = Xp::ParseTomlTimestamps, .name = "parse-toml-timestamps", .description = R"( Allow parsing of timestamps in builtins.fromTOML. )", .trackingUrl = "https://github.com/NixOS/nix/milestone/45", }, { .tag = Xp::ReadOnlyLocalStore, .name = "read-only-local-store", .description = R"( Allow the use of the `read-only` parameter in [local store](@docroot@/store/types/local-store.md) URIs. )", .trackingUrl = "https://github.com/NixOS/nix/milestone/46", }, { .tag = Xp::LocalOverlayStore, .name = "local-overlay-store", .description = R"( Allow the use of [local overlay store](@docroot@/command-ref/new-cli/nix3-help-stores.md#local-overlay-store). )", .trackingUrl = "https://github.com/NixOS/nix/milestone/50", }, { .tag = Xp::ConfigurableImpureEnv, .name = "configurable-impure-env", .description = R"( Allow the use of the [impure-env](@docroot@/command-ref/conf-file.md#conf-impure-env) setting. )", .trackingUrl = "https://github.com/NixOS/nix/milestone/37", }, { .tag = Xp::MountedSSHStore, .name = "mounted-ssh-store", .description = R"( Allow the use of the [`mounted SSH store`](@docroot@/command-ref/new-cli/nix3-help-stores.html#experimental-ssh-store-with-filesystem-mounted). )", .trackingUrl = "https://github.com/NixOS/nix/milestone/43", }, { .tag = Xp::VerifiedFetches, .name = "verified-fetches", .description = R"( Enables verification of git commit signatures through the [`fetchGit`](@docroot@/language/builtins.md#builtins-fetchGit) built-in. )", .trackingUrl = "https://github.com/NixOS/nix/milestone/48", }, { .tag = Xp::PipeOperators, .name = "pipe-operators", .description = R"( Add `|>` and `<|` operators to the Nix language. )", .trackingUrl = "https://github.com/NixOS/nix/milestone/55", }, }}; static_assert( []() constexpr { for (auto [index, feature] : enumerate(xpFeatureDetails)) if (index != (size_t)feature.tag) return false; return true; }(), "array order does not match enum tag order"); const std::optional<ExperimentalFeature> parseExperimentalFeature(const std::string_view & name) { using ReverseXpMap = std::map<std::string_view, ExperimentalFeature>; static std::unique_ptr<ReverseXpMap> reverseXpMap = []() { auto reverseXpMap = std::make_unique<ReverseXpMap>(); for (auto & xpFeature : xpFeatureDetails) (*reverseXpMap)[xpFeature.name] = xpFeature.tag; return reverseXpMap; }(); if (auto feature = get(*reverseXpMap, name)) return *feature; else return std::nullopt; } std::string_view showExperimentalFeature(const ExperimentalFeature tag) { assert((size_t)tag < xpFeatureDetails.size()); return xpFeatureDetails[(size_t)tag].name; } nlohmann::json documentExperimentalFeatures() { StringMap res; for (auto & xpFeature : xpFeatureDetails) { std::stringstream docOss; docOss << stripIndentation(xpFeature.description); docOss << fmt("\nRefer to [%1% tracking issue](%2%) for feature tracking.", xpFeature.name, xpFeature.trackingUrl); res[std::string{xpFeature.name}] = trim(docOss.str()); } return (nlohmann::json) res; } std::set<ExperimentalFeature> parseFeatures(const std::set<std::string> & rawFeatures) { std::set<ExperimentalFeature> res; for (auto & rawFeature : rawFeatures) if (auto feature = parseExperimentalFeature(rawFeature)) res.insert(*feature); return res; } MissingExperimentalFeature::MissingExperimentalFeature(ExperimentalFeature feature) : Error("experimental Nix feature '%1%' is disabled; add '--extra-experimental-features %1%' to enable it", showExperimentalFeature(feature)) , missingFeature(feature) {} std::ostream & operator <<(std::ostream & str, const ExperimentalFeature & feature) { return str << showExperimentalFeature(feature); } void to_json(nlohmann::json & j, const ExperimentalFeature & feature) { j = showExperimentalFeature(feature); } void from_json(const nlohmann::json & j, ExperimentalFeature & feature) { const std::string input = j; const auto parsed = parseExperimentalFeature(input); if (parsed.has_value()) feature = *parsed; else throw Error("Unknown experimental feature '%s' in JSON input", input); } }
14,049
C++
.cc
343
32.183673
155
0.61606
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,864
url.cc
NixOS_nix/src/libutil/url.cc
#include "url.hh" #include "url-parts.hh" #include "util.hh" #include "split.hh" #include "canon-path.hh" namespace nix { std::regex refRegex(refRegexS, std::regex::ECMAScript); std::regex badGitRefRegex(badGitRefRegexS, std::regex::ECMAScript); std::regex revRegex(revRegexS, std::regex::ECMAScript); ParsedURL parseURL(const std::string & url) { static std::regex uriRegex( "((" + schemeNameRegex + "):" + "(?:(?://(" + authorityRegex + ")(" + absPathRegex + "))|(/?" + pathRegex + ")))" + "(?:\\?(" + queryRegex + "))?" + "(?:#(" + fragmentRegex + "))?", std::regex::ECMAScript); std::smatch match; if (std::regex_match(url, match, uriRegex)) { auto & base = match[1]; std::string scheme = match[2]; auto authority = match[3].matched ? std::optional<std::string>(match[3]) : std::nullopt; std::string path = match[4].matched ? match[4] : match[5]; auto & query = match[6]; auto & fragment = match[7]; auto transportIsFile = parseUrlScheme(scheme).transport == "file"; if (authority && *authority != "" && transportIsFile) throw BadURL("file:// URL '%s' has unexpected authority '%s'", url, *authority); if (transportIsFile && path.empty()) path = "/"; return ParsedURL{ .url = url, .base = base, .scheme = scheme, .authority = authority, .path = percentDecode(path), .query = decodeQuery(query), .fragment = percentDecode(std::string(fragment)) }; } else throw BadURL("'%s' is not a valid URL", url); } std::string percentDecode(std::string_view in) { std::string decoded; for (size_t i = 0; i < in.size(); ) { if (in[i] == '%') { if (i + 2 >= in.size()) throw BadURL("invalid URI parameter '%s'", in); try { decoded += std::stoul(std::string(in, i + 1, 2), 0, 16); i += 3; } catch (...) { throw BadURL("invalid URI parameter '%s'", in); } } else decoded += in[i++]; } return decoded; } std::map<std::string, std::string> decodeQuery(const std::string & query) { std::map<std::string, std::string> result; for (auto s : tokenizeString<Strings>(query, "&")) { auto e = s.find('='); if (e == std::string::npos) { warn("dubious URI query '%s' is missing equal sign '%s', ignoring", s, "="); continue; } result.emplace( s.substr(0, e), percentDecode(std::string_view(s).substr(e + 1))); } return result; } const static std::string allowedInQuery = ":@/?"; const static std::string allowedInPath = ":@/"; std::string percentEncode(std::string_view s, std::string_view keep) { std::string res; for (auto & c : s) // unreserved + keep if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || strchr("-._~", c) || keep.find(c) != std::string::npos) res += c; else res += fmt("%%%02X", c & 0xFF); return res; } std::string encodeQuery(const std::map<std::string, std::string> & ss) { std::string res; bool first = true; for (auto & [name, value] : ss) { if (!first) res += '&'; first = false; res += percentEncode(name, allowedInQuery); res += '='; res += percentEncode(value, allowedInQuery); } return res; } std::string ParsedURL::to_string() const { return scheme + ":" + (authority ? "//" + *authority : "") + percentEncode(path, allowedInPath) + (query.empty() ? "" : "?" + encodeQuery(query)) + (fragment.empty() ? "" : "#" + percentEncode(fragment)); } bool ParsedURL::operator ==(const ParsedURL & other) const noexcept { return scheme == other.scheme && authority == other.authority && path == other.path && query == other.query && fragment == other.fragment; } ParsedURL ParsedURL::canonicalise() { ParsedURL res(*this); res.path = CanonPath(res.path).abs(); return res; } /** * Parse a URL scheme of the form '(applicationScheme\+)?transportScheme' * into a tuple '(applicationScheme, transportScheme)' * * > parseUrlScheme("http") == ParsedUrlScheme{ {}, "http"} * > parseUrlScheme("tarball+http") == ParsedUrlScheme{ {"tarball"}, "http"} */ ParsedUrlScheme parseUrlScheme(std::string_view scheme) { auto application = splitPrefixTo(scheme, '+'); auto transport = scheme; return ParsedUrlScheme { .application = application, .transport = transport, }; } std::string fixGitURL(const std::string & url) { std::regex scpRegex("([^/]*)@(.*):(.*)"); if (!hasPrefix(url, "/") && std::regex_match(url, scpRegex)) return std::regex_replace(url, scpRegex, "ssh://$1@$2/$3"); if (hasPrefix(url, "file:")) return url; if (url.find("://") == std::string::npos) { return (ParsedURL { .scheme = "file", .authority = "", .path = url }).to_string(); } return url; } // https://www.rfc-editor.org/rfc/rfc3986#section-3.1 bool isValidSchemeName(std::string_view s) { static std::regex regex(schemeNameRegex, std::regex::ECMAScript); return std::regex_match(s.begin(), s.end(), regex, std::regex_constants::match_default); } }
5,623
C++
.cc
172
25.97093
92
0.551889
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,865
config-global.cc
NixOS_nix/src/libutil/config-global.cc
#include "config-global.hh" #include <nlohmann/json.hpp> namespace nix { bool GlobalConfig::set(const std::string & name, const std::string & value) { for (auto & config : *configRegistrations) if (config->set(name, value)) return true; unknownSettings.emplace(name, value); return false; } void GlobalConfig::getSettings(std::map<std::string, SettingInfo> & res, bool overriddenOnly) { for (auto & config : *configRegistrations) config->getSettings(res, overriddenOnly); } void GlobalConfig::resetOverridden() { for (auto & config : *configRegistrations) config->resetOverridden(); } nlohmann::json GlobalConfig::toJSON() { auto res = nlohmann::json::object(); for (const auto & config : *configRegistrations) res.update(config->toJSON()); return res; } std::string GlobalConfig::toKeyValue() { std::string res; std::map<std::string, Config::SettingInfo> settings; globalConfig.getSettings(settings); for (const auto & s : settings) res += fmt("%s = %s\n", s.first, s.second.value); return res; } void GlobalConfig::convertToArgs(Args & args, const std::string & category) { for (auto & config : *configRegistrations) config->convertToArgs(args, category); } GlobalConfig globalConfig; GlobalConfig::ConfigRegistrations * GlobalConfig::configRegistrations; GlobalConfig::Register::Register(Config * config) { if (!configRegistrations) configRegistrations = new ConfigRegistrations; configRegistrations->emplace_back(config); } ExperimentalFeatureSettings experimentalFeatureSettings; static GlobalConfig::Register rSettings(&experimentalFeatureSettings); }
1,706
C++
.cc
53
28.396226
93
0.729383
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,866
thread-pool.cc
NixOS_nix/src/libutil/thread-pool.cc
#include "thread-pool.hh" #include "signals.hh" #include "util.hh" namespace nix { ThreadPool::ThreadPool(size_t _maxThreads) : maxThreads(_maxThreads) { if (!maxThreads) { maxThreads = std::thread::hardware_concurrency(); if (!maxThreads) maxThreads = 1; } debug("starting pool of %d threads", maxThreads - 1); } ThreadPool::~ThreadPool() { shutdown(); } void ThreadPool::shutdown() { std::vector<std::thread> workers; { auto state(state_.lock()); quit = true; std::swap(workers, state->workers); } if (workers.empty()) return; debug("reaping %d worker threads", workers.size()); work.notify_all(); for (auto & thr : workers) thr.join(); } void ThreadPool::enqueue(const work_t & t) { auto state(state_.lock()); if (quit) throw ThreadPoolShutDown("cannot enqueue a work item while the thread pool is shutting down"); state->pending.push(t); /* Note: process() also executes items, so count it as a worker. */ if (state->pending.size() > state->workers.size() + 1 && state->workers.size() + 1 < maxThreads) state->workers.emplace_back(&ThreadPool::doWork, this, false); work.notify_one(); } void ThreadPool::process() { state_.lock()->draining = true; /* Do work until no more work is pending or active. */ try { doWork(true); auto state(state_.lock()); assert(quit); if (state->exception) std::rethrow_exception(state->exception); } catch (...) { /* In the exceptional case, some workers may still be active. They may be referencing the stack frame of the caller. So wait for them to finish. (~ThreadPool also does this, but it might be destroyed after objects referenced by the work item lambdas.) */ shutdown(); throw; } } void ThreadPool::doWork(bool mainThread) { ReceiveInterrupts receiveInterrupts; #ifndef _WIN32 // Does Windows need anything similar for async exit handling? if (!mainThread) unix::interruptCheck = [&]() { return (bool) quit; }; #endif bool didWork = false; std::exception_ptr exc; while (true) { work_t w; { auto state(state_.lock()); if (didWork) { assert(state->active); state->active--; if (exc) { if (!state->exception) { state->exception = exc; // Tell the other workers to quit. quit = true; work.notify_all(); } else { /* Print the exception, since we can't propagate it. */ try { std::rethrow_exception(exc); } catch (const Interrupted &) { // The interrupted state may be picked up by multiple // workers, which is expected, so we should ignore // it silently and let the first one bubble up, // rethrown via the original state->exception. } catch (const ThreadPoolShutDown &) { // Similarly expected. } catch (std::exception & e) { ignoreExceptionExceptInterrupt(); } } } } /* Wait until a work item is available or we're asked to quit. */ while (true) { if (quit) return; if (!state->pending.empty()) break; /* If there are no active or pending items, and the main thread is running process(), then no new items can be added. So exit. */ if (!state->active && state->draining) { quit = true; work.notify_all(); return; } state.wait(work); } w = std::move(state->pending.front()); state->pending.pop(); state->active++; } try { w(); } catch (...) { exc = std::current_exception(); } didWork = true; } } }
4,459
C++
.cc
130
23.169231
102
0.510708
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
10,867
executable-path.cc
NixOS_nix/src/libutil/executable-path.cc
#include "environment-variables.hh" #include "executable-path.hh" #include "strings-inline.hh" #include "util.hh" #include "file-path-impl.hh" namespace nix { namespace fs { using namespace std::filesystem; } constexpr static const OsStringView path_var_separator{ &ExecutablePath::separator, 1, }; ExecutablePath ExecutablePath::load() { // "If PATH is unset or is set to null, the path search is // implementation-defined." // https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html#tag_08_03 return ExecutablePath::parse(getEnvOs(OS_STR("PATH")).value_or(OS_STR(""))); } ExecutablePath ExecutablePath::parse(const OsString & path) { auto strings = path.empty() ? (std::list<OsString>{}) : basicSplitString<std::list<OsString>, OsChar>(path, path_var_separator); std::vector<fs::path> ret; ret.reserve(strings.size()); std::transform( std::make_move_iterator(strings.begin()), std::make_move_iterator(strings.end()), std::back_inserter(ret), [](OsString && str) { return fs::path{ str.empty() // "A zero-length prefix is a legacy feature that // indicates the current working directory. It // appears as two adjacent <colon> characters // ("::"), as an initial <colon> preceding the rest // of the list, or as a trailing <colon> following // the rest of the list." // https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html#tag_08_03 ? OS_STR(".") : std::move(str), }; }); return {ret}; } OsString ExecutablePath::render() const { std::vector<PathViewNG> path2; path2.reserve(directories.size()); for (auto & p : directories) path2.push_back(p.native()); return basicConcatStringsSep(path_var_separator, path2); } std::optional<fs::path> ExecutablePath::findName(const OsString & exe, std::function<bool(const fs::path &)> isExecutable) const { // "If the pathname being sought contains a <slash>, the search // through the path prefixes shall not be performed." // https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html#tag_08_03 assert(OsPathTrait<fs::path::value_type>::rfindPathSep(exe) == exe.npos); for (auto & dir : directories) { auto candidate = dir / exe; if (isExecutable(candidate)) return std::filesystem::canonical(candidate); } return std::nullopt; } fs::path ExecutablePath::findPath(const fs::path & exe, std::function<bool(const fs::path &)> isExecutable) const { // "If the pathname being sought contains a <slash>, the search // through the path prefixes shall not be performed." // https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html#tag_08_03 if (exe.filename() == exe) { auto resOpt = findName(exe, isExecutable); if (resOpt) return *resOpt; else throw ExecutableLookupError("Could not find executable '%s'", exe.string()); } else { return exe; } } } // namespace nix
3,276
C++
.cc
84
31.928571
113
0.637193
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,868
config.cc
NixOS_nix/src/libutil/config.cc
#include "config.hh" #include "args.hh" #include "abstract-setting-to-json.hh" #include "environment-variables.hh" #include "experimental-features.hh" #include "util.hh" #include "file-system.hh" #include "config-impl.hh" #include <nlohmann/json.hpp> #include "strings.hh" namespace nix { Config::Config(StringMap initials) : AbstractConfig(std::move(initials)) { } bool Config::set(const std::string & name, const std::string & value) { bool append = false; auto i = _settings.find(name); if (i == _settings.end()) { if (hasPrefix(name, "extra-")) { i = _settings.find(std::string(name, 6)); if (i == _settings.end() || !i->second.setting->isAppendable()) return false; append = true; } else return false; } i->second.setting->set(value, append); i->second.setting->overridden = true; return true; } void Config::addSetting(AbstractSetting * setting) { _settings.emplace(setting->name, Config::SettingData{false, setting}); for (const auto & alias : setting->aliases) _settings.emplace(alias, Config::SettingData{true, setting}); bool set = false; if (auto i = unknownSettings.find(setting->name); i != unknownSettings.end()) { setting->set(std::move(i->second)); setting->overridden = true; unknownSettings.erase(i); set = true; } for (auto & alias : setting->aliases) { if (auto i = unknownSettings.find(alias); i != unknownSettings.end()) { if (set) warn("setting '%s' is set, but it's an alias of '%s' which is also set", alias, setting->name); else { setting->set(std::move(i->second)); setting->overridden = true; unknownSettings.erase(i); set = true; } } } } AbstractConfig::AbstractConfig(StringMap initials) : unknownSettings(std::move(initials)) { } void AbstractConfig::warnUnknownSettings() { for (const auto & s : unknownSettings) warn("unknown setting '%s'", s.first); } void AbstractConfig::reapplyUnknownSettings() { auto unknownSettings2 = std::move(unknownSettings); unknownSettings = {}; for (auto & s : unknownSettings2) set(s.first, s.second); } void Config::getSettings(std::map<std::string, SettingInfo> & res, bool overriddenOnly) { for (const auto & opt : _settings) if (!opt.second.isAlias && (!overriddenOnly || opt.second.setting->overridden) && experimentalFeatureSettings.isEnabled(opt.second.setting->experimentalFeature)) res.emplace(opt.first, SettingInfo{opt.second.setting->to_string(), opt.second.setting->description}); } /** * Parse configuration in `contents`, and also the configuration files included from there, with their location specified relative to `path`. * * `contents` and `path` represent the file that is being parsed. * The result is only an intermediate list of key-value pairs of strings. * More parsing according to the settings-specific semantics is being done by `loadConfFile` in `libstore/globals.cc`. */ static void parseConfigFiles(const std::string & contents, const std::string & path, std::vector<std::pair<std::string, std::string>> & parsedContents) { unsigned int pos = 0; while (pos < contents.size()) { std::string line; while (pos < contents.size() && contents[pos] != '\n') line += contents[pos++]; pos++; if (auto hash = line.find('#'); hash != line.npos) line = std::string(line, 0, hash); auto tokens = tokenizeString<std::vector<std::string>>(line); if (tokens.empty()) continue; if (tokens.size() < 2) throw UsageError("syntax error in configuration line '%1%' in '%2%'", line, path); auto include = false; auto ignoreMissing = false; if (tokens[0] == "include") include = true; else if (tokens[0] == "!include") { include = true; ignoreMissing = true; } if (include) { if (tokens.size() != 2) throw UsageError("syntax error in configuration line '%1%' in '%2%'", line, path); auto p = absPath(tokens[1], dirOf(path)); if (pathExists(p)) { try { std::string includedContents = readFile(p); parseConfigFiles(includedContents, p, parsedContents); } catch (SystemError &) { // TODO: Do we actually want to ignore this? Or is it better to fail? } } else if (!ignoreMissing) { throw Error("file '%1%' included from '%2%' not found", p, path); } continue; } if (tokens[1] != "=") throw UsageError("syntax error in configuration line '%1%' in '%2%'", line, path); std::string name = std::move(tokens[0]); auto i = tokens.begin(); advance(i, 2); parsedContents.push_back({ std::move(name), concatStringsSep(" ", Strings(i, tokens.end())), }); }; } void AbstractConfig::applyConfig(const std::string & contents, const std::string & path) { std::vector<std::pair<std::string, std::string>> parsedContents; parseConfigFiles(contents, path, parsedContents); // First apply experimental-feature related settings for (const auto & [name, value] : parsedContents) if (name == "experimental-features" || name == "extra-experimental-features") set(name, value); // Then apply other settings // XXX: NIX_PATH must override the regular setting! This is done in `initGC()` // Environment variables overriding settings should probably be part of the Config mechanism, // but at the time of writing it's not worth building that for just one thing for (const auto & [name, value] : parsedContents) { if (name != "experimental-features" && name != "extra-experimental-features") { if ((name == "nix-path" || name == "extra-nix-path") && getEnv("NIX_PATH").has_value()) { continue; } set(name, value); } } } void Config::resetOverridden() { for (auto & s : _settings) s.second.setting->overridden = false; } nlohmann::json Config::toJSON() { auto res = nlohmann::json::object(); for (const auto & s : _settings) if (!s.second.isAlias) res.emplace(s.first, s.second.setting->toJSON()); return res; } std::string Config::toKeyValue() { std::string res; for (const auto & s : _settings) if (s.second.isAlias) res += fmt("%s = %s\n", s.first, s.second.setting->to_string()); return res; } void Config::convertToArgs(Args & args, const std::string & category) { for (auto & s : _settings) { if (!s.second.isAlias) s.second.setting->convertToArg(args, category); } } AbstractSetting::AbstractSetting( const std::string & name, const std::string & description, const std::set<std::string> & aliases, std::optional<ExperimentalFeature> experimentalFeature) : name(name) , description(stripIndentation(description)) , aliases(aliases) , experimentalFeature(std::move(experimentalFeature)) { } AbstractSetting::~AbstractSetting() { // Check against a gcc miscompilation causing our constructor // not to run (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80431). assert(created == 123); } nlohmann::json AbstractSetting::toJSON() { return nlohmann::json(toJSONObject()); } std::map<std::string, nlohmann::json> AbstractSetting::toJSONObject() const { std::map<std::string, nlohmann::json> obj; obj.emplace("description", description); obj.emplace("aliases", aliases); if (experimentalFeature) obj.emplace("experimentalFeature", *experimentalFeature); else obj.emplace("experimentalFeature", nullptr); return obj; } void AbstractSetting::convertToArg(Args & args, const std::string & category) { } bool AbstractSetting::isOverridden() const { return overridden; } template<> std::string BaseSetting<std::string>::parse(const std::string & str) const { return str; } template<> std::string BaseSetting<std::string>::to_string() const { return value; } template<> std::optional<std::string> BaseSetting<std::optional<std::string>>::parse(const std::string & str) const { if (str == "") return std::nullopt; else return { str }; } template<> std::string BaseSetting<std::optional<std::string>>::to_string() const { return value ? *value : ""; } template<> bool BaseSetting<bool>::parse(const std::string & str) const { if (str == "true" || str == "yes" || str == "1") return true; else if (str == "false" || str == "no" || str == "0") return false; else throw UsageError("Boolean setting '%s' has invalid value '%s'", name, str); } template<> std::string BaseSetting<bool>::to_string() const { return value ? "true" : "false"; } template<> void BaseSetting<bool>::convertToArg(Args & args, const std::string & category) { args.addFlag({ .longName = name, .aliases = aliases, .description = fmt("Enable the `%s` setting.", name), .category = category, .handler = {[this] { override(true); }}, .experimentalFeature = experimentalFeature, }); args.addFlag({ .longName = "no-" + name, .aliases = aliases, .description = fmt("Disable the `%s` setting.", name), .category = category, .handler = {[this] { override(false); }}, .experimentalFeature = experimentalFeature, }); } template<> Strings BaseSetting<Strings>::parse(const std::string & str) const { return tokenizeString<Strings>(str); } template<> void BaseSetting<Strings>::appendOrSet(Strings newValue, bool append) { if (!append) value.clear(); value.insert(value.end(), std::make_move_iterator(newValue.begin()), std::make_move_iterator(newValue.end())); } template<> std::string BaseSetting<Strings>::to_string() const { return concatStringsSep(" ", value); } template<> StringSet BaseSetting<StringSet>::parse(const std::string & str) const { return tokenizeString<StringSet>(str); } template<> void BaseSetting<StringSet>::appendOrSet(StringSet newValue, bool append) { if (!append) value.clear(); value.insert(std::make_move_iterator(newValue.begin()), std::make_move_iterator(newValue.end())); } template<> std::string BaseSetting<StringSet>::to_string() const { return concatStringsSep(" ", value); } template<> std::set<ExperimentalFeature> BaseSetting<std::set<ExperimentalFeature>>::parse(const std::string & str) const { std::set<ExperimentalFeature> res; for (auto & s : tokenizeString<StringSet>(str)) { if (auto thisXpFeature = parseExperimentalFeature(s); thisXpFeature) { res.insert(thisXpFeature.value()); if (thisXpFeature.value() == Xp::Flakes) res.insert(Xp::FetchTree); } else warn("unknown experimental feature '%s'", s); } return res; } template<> void BaseSetting<std::set<ExperimentalFeature>>::appendOrSet(std::set<ExperimentalFeature> newValue, bool append) { if (!append) value.clear(); value.insert(std::make_move_iterator(newValue.begin()), std::make_move_iterator(newValue.end())); } template<> std::string BaseSetting<std::set<ExperimentalFeature>>::to_string() const { StringSet stringifiedXpFeatures; for (const auto & feature : value) stringifiedXpFeatures.insert(std::string(showExperimentalFeature(feature))); return concatStringsSep(" ", stringifiedXpFeatures); } template<> StringMap BaseSetting<StringMap>::parse(const std::string & str) const { StringMap res; for (const auto & s : tokenizeString<Strings>(str)) { if (auto eq = s.find_first_of('='); s.npos != eq) res.emplace(std::string(s, 0, eq), std::string(s, eq + 1)); // else ignored } return res; } template<> void BaseSetting<StringMap>::appendOrSet(StringMap newValue, bool append) { if (!append) value.clear(); value.insert(std::make_move_iterator(newValue.begin()), std::make_move_iterator(newValue.end())); } template<> std::string BaseSetting<StringMap>::to_string() const { return std::transform_reduce(value.cbegin(), value.cend(), std::string{}, [](const auto & l, const auto &r) { return l + " " + r; }, [](const auto & kvpair){ return kvpair.first + "=" + kvpair.second; }); } template class BaseSetting<int>; template class BaseSetting<unsigned int>; template class BaseSetting<long>; template class BaseSetting<unsigned long>; template class BaseSetting<long long>; template class BaseSetting<unsigned long long>; template class BaseSetting<bool>; template class BaseSetting<std::string>; template class BaseSetting<Strings>; template class BaseSetting<StringSet>; template class BaseSetting<StringMap>; template class BaseSetting<std::set<ExperimentalFeature>>; static Path parsePath(const AbstractSetting & s, const std::string & str) { if (str == "") throw UsageError("setting '%s' is a path and paths cannot be empty", s.name); else return canonPath(str); } PathSetting::PathSetting(Config * options, const Path & def, const std::string & name, const std::string & description, const std::set<std::string> & aliases) : BaseSetting<Path>(def, true, name, description, aliases) { options->addSetting(this); } Path PathSetting::parse(const std::string & str) const { return parsePath(*this, str); } OptionalPathSetting::OptionalPathSetting(Config * options, const std::optional<Path> & def, const std::string & name, const std::string & description, const std::set<std::string> & aliases) : BaseSetting<std::optional<Path>>(def, true, name, description, aliases) { options->addSetting(this); } std::optional<Path> OptionalPathSetting::parse(const std::string & str) const { if (str == "") return std::nullopt; else return parsePath(*this, str); } void OptionalPathSetting::operator =(const std::optional<Path> & v) { this->assign(v); } bool ExperimentalFeatureSettings::isEnabled(const ExperimentalFeature & feature) const { auto & f = experimentalFeatures.get(); return std::find(f.begin(), f.end(), feature) != f.end(); } void ExperimentalFeatureSettings::require(const ExperimentalFeature & feature) const { if (!isEnabled(feature)) throw MissingExperimentalFeature(feature); } bool ExperimentalFeatureSettings::isEnabled(const std::optional<ExperimentalFeature> & feature) const { return !feature || isEnabled(*feature); } void ExperimentalFeatureSettings::require(const std::optional<ExperimentalFeature> & feature) const { if (feature) require(*feature); } }
15,160
C++
.cc
415
30.978313
153
0.653125
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,869
util.cc
NixOS_nix/src/libutil/util.cc
#include "util.hh" #include "fmt.hh" #include "file-path.hh" #include "signals.hh" #include <array> #include <cctype> #include <iostream> #include <regex> #include <sodium.h> #include <boost/lexical_cast.hpp> #include <stdint.h> #ifdef NDEBUG #error "Nix may not be built with assertions disabled (i.e. with -DNDEBUG)." #endif namespace nix { void initLibUtil() { // Check that exception handling works. Exception handling has been observed // not to work on darwin when the linker flags aren't quite right. // In this case we don't want to expose the user to some unrelated uncaught // exception, but rather tell them exactly that exception handling is // broken. // When exception handling fails, the message tends to be printed by the // C++ runtime, followed by an abort. // For example on macOS we might see an error such as // libc++abi: terminating with uncaught exception of type nix::SystemError: error: C++ exception handling is broken. This would appear to be a problem with the way Nix was compiled and/or linked and/or loaded. bool caught = false; try { throwExceptionSelfCheck(); } catch (const nix::Error & _e) { caught = true; } // This is not actually the main point of this check, but let's make sure anyway: assert(caught); if (sodium_init() == -1) throw Error("could not initialise libsodium"); } ////////////////////////////////////////////////////////////////////// std::vector<char *> stringsToCharPtrs(const Strings & ss) { std::vector<char *> res; for (auto & s : ss) res.push_back((char *) s.c_str()); res.push_back(0); return res; } ////////////////////////////////////////////////////////////////////// std::string chomp(std::string_view s) { size_t i = s.find_last_not_of(" \n\r\t"); return i == s.npos ? "" : std::string(s, 0, i + 1); } std::string trim(std::string_view s, std::string_view whitespace) { auto i = s.find_first_not_of(whitespace); if (i == s.npos) return ""; auto j = s.find_last_not_of(whitespace); return std::string(s, i, j == s.npos ? j : j - i + 1); } std::string replaceStrings( std::string res, std::string_view from, std::string_view to) { if (from.empty()) return res; size_t pos = 0; while ((pos = res.find(from, pos)) != res.npos) { res.replace(pos, from.size(), to); pos += to.size(); } return res; } std::string rewriteStrings(std::string s, const StringMap & rewrites) { for (auto & i : rewrites) { if (i.first == i.second) continue; size_t j = 0; while ((j = s.find(i.first, j)) != s.npos) s.replace(j, i.first.size(), i.second); } return s; } template<class N> std::optional<N> string2Int(const std::string_view s) { if (s.substr(0, 1) == "-" && !std::numeric_limits<N>::is_signed) return std::nullopt; try { return boost::lexical_cast<N>(s.data(), s.size()); } catch (const boost::bad_lexical_cast &) { return std::nullopt; } } // Explicitly instantiated in one place for faster compilation template std::optional<unsigned char> string2Int<unsigned char>(const std::string_view s); template std::optional<unsigned short> string2Int<unsigned short>(const std::string_view s); template std::optional<unsigned int> string2Int<unsigned int>(const std::string_view s); template std::optional<unsigned long> string2Int<unsigned long>(const std::string_view s); template std::optional<unsigned long long> string2Int<unsigned long long>(const std::string_view s); template std::optional<signed char> string2Int<signed char>(const std::string_view s); template std::optional<signed short> string2Int<signed short>(const std::string_view s); template std::optional<signed int> string2Int<signed int>(const std::string_view s); template std::optional<signed long> string2Int<signed long>(const std::string_view s); template std::optional<signed long long> string2Int<signed long long>(const std::string_view s); template<class N> std::optional<N> string2Float(const std::string_view s) { try { return boost::lexical_cast<N>(s.data(), s.size()); } catch (const boost::bad_lexical_cast &) { return std::nullopt; } } template std::optional<double> string2Float<double>(const std::string_view s); template std::optional<float> string2Float<float>(const std::string_view s); std::string renderSize(uint64_t value, bool align) { static const std::array<char, 9> prefixes{{ 'K', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y' }}; size_t power = 0; double res = value; while (res > 1024 && power < prefixes.size()) { ++power; res /= 1024; } return fmt(align ? "%6.1f %ciB" : "%.1f %ciB", power == 0 ? res / 1024 : res, prefixes.at(power)); } bool hasPrefix(std::string_view s, std::string_view prefix) { return s.compare(0, prefix.size(), prefix) == 0; } bool hasSuffix(std::string_view s, std::string_view suffix) { return s.size() >= suffix.size() && s.substr(s.size() - suffix.size()) == suffix; } std::string toLower(std::string s) { for (auto & c : s) c = std::tolower(c); return s; } std::string shellEscape(const std::string_view s) { std::string r; r.reserve(s.size() + 2); r += '\''; for (auto & i : s) if (i == '\'') r += "'\\''"; else r += i; r += '\''; return r; } void ignoreExceptionInDestructor(Verbosity lvl) { /* Make sure no exceptions leave this function. printError() also throws when remote is closed. */ try { try { throw; } catch (std::exception & e) { printMsg(lvl, "error (ignored): %1%", e.what()); } } catch (...) { } } void ignoreExceptionExceptInterrupt(Verbosity lvl) { try { throw; } catch (const Interrupted & e) { throw; } catch (std::exception & e) { printMsg(lvl, "error (ignored): %1%", e.what()); } } constexpr char base64Chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; std::string base64Encode(std::string_view s) { std::string res; res.reserve((s.size() + 2) / 3 * 4); int data = 0, nbits = 0; for (char c : s) { data = data << 8 | (unsigned char) c; nbits += 8; while (nbits >= 6) { nbits -= 6; res.push_back(base64Chars[data >> nbits & 0x3f]); } } if (nbits) res.push_back(base64Chars[data << (6 - nbits) & 0x3f]); while (res.size() % 4) res.push_back('='); return res; } std::string base64Decode(std::string_view s) { constexpr char npos = -1; constexpr std::array<char, 256> base64DecodeChars = [&] { std::array<char, 256> result{}; for (auto& c : result) c = npos; for (int i = 0; i < 64; i++) result[base64Chars[i]] = i; return result; }(); std::string res; // Some sequences are missing the padding consisting of up to two '='. // vvv res.reserve((s.size() + 2) / 4 * 3); unsigned int d = 0, bits = 0; for (char c : s) { if (c == '=') break; if (c == '\n') continue; char digit = base64DecodeChars[(unsigned char) c]; if (digit == npos) throw FormatError("invalid character in Base64 string: '%c'", c); bits += 6; d = d << 6 | digit; if (bits >= 8) { res.push_back(d >> (bits - 8) & 0xff); bits -= 8; } } return res; } std::string stripIndentation(std::string_view s) { size_t minIndent = 10000; size_t curIndent = 0; bool atStartOfLine = true; for (auto & c : s) { if (atStartOfLine && c == ' ') curIndent++; else if (c == '\n') { if (atStartOfLine) minIndent = std::max(minIndent, curIndent); curIndent = 0; atStartOfLine = true; } else { if (atStartOfLine) { minIndent = std::min(minIndent, curIndent); atStartOfLine = false; } } } std::string res; size_t pos = 0; while (pos < s.size()) { auto eol = s.find('\n', pos); if (eol == s.npos) eol = s.size(); if (eol - pos > minIndent) res.append(s.substr(pos + minIndent, eol - pos - minIndent)); res.push_back('\n'); pos = eol + 1; } return res; } std::pair<std::string_view, std::string_view> getLine(std::string_view s) { auto newline = s.find('\n'); if (newline == s.npos) { return {s, ""}; } else { auto line = s.substr(0, newline); if (!line.empty() && line[line.size() - 1] == '\r') line = line.substr(0, line.size() - 1); return {line, s.substr(newline + 1)}; } } std::string showBytes(uint64_t bytes) { return fmt("%.2f MiB", bytes / (1024.0 * 1024.0)); } }
9,021
C++
.cc
271
27.96679
213
0.593901
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,870
logging.cc
NixOS_nix/src/libutil/logging.cc
#include "logging.hh" #include "file-descriptor.hh" #include "environment-variables.hh" #include "terminal.hh" #include "util.hh" #include "config-global.hh" #include "source-path.hh" #include "position.hh" #include <atomic> #include <sstream> #include <nlohmann/json.hpp> #include <iostream> namespace nix { LoggerSettings loggerSettings; static GlobalConfig::Register rLoggerSettings(&loggerSettings); static thread_local ActivityId curActivity = 0; ActivityId getCurActivity() { return curActivity; } void setCurActivity(const ActivityId activityId) { curActivity = activityId; } Logger * logger = makeSimpleLogger(true); void Logger::warn(const std::string & msg) { log(lvlWarn, ANSI_WARNING "warning:" ANSI_NORMAL " " + msg); } void Logger::writeToStdout(std::string_view s) { Descriptor standard_out = getStandardOutput(); writeFull(standard_out, s); writeFull(standard_out, "\n"); } class SimpleLogger : public Logger { public: bool systemd, tty; bool printBuildLogs; SimpleLogger(bool printBuildLogs) : printBuildLogs(printBuildLogs) { systemd = getEnv("IN_SYSTEMD") == "1"; tty = isTTY(); } bool isVerbose() override { return printBuildLogs; } void log(Verbosity lvl, std::string_view s) override { if (lvl > verbosity) return; std::string prefix; if (systemd) { char c; switch (lvl) { case lvlError: c = '3'; break; case lvlWarn: c = '4'; break; case lvlNotice: case lvlInfo: c = '5'; break; case lvlTalkative: case lvlChatty: c = '6'; break; case lvlDebug: case lvlVomit: c = '7'; break; default: c = '7'; break; // should not happen, and missing enum case is reported by -Werror=switch-enum } prefix = std::string("<") + c + ">"; } writeToStderr(prefix + filterANSIEscapes(s, !tty) + "\n"); } void logEI(const ErrorInfo & ei) override { std::ostringstream oss; showErrorInfo(oss, ei, loggerSettings.showTrace.get()); log(ei.level, toView(oss)); } void startActivity(ActivityId act, Verbosity lvl, ActivityType type, const std::string & s, const Fields & fields, ActivityId parent) override { if (lvl <= verbosity && !s.empty()) log(lvl, s + "..."); } void result(ActivityId act, ResultType type, const Fields & fields) override { if (type == resBuildLogLine && printBuildLogs) { auto lastLine = fields[0].s; printError(lastLine); } else if (type == resPostBuildLogLine && printBuildLogs) { auto lastLine = fields[0].s; printError("post-build-hook: " + lastLine); } } }; Verbosity verbosity = lvlInfo; void writeToStderr(std::string_view s) { try { writeFull( getStandardError(), s, false); } catch (SystemError & e) { /* Ignore failing writes to stderr. We need to ignore write errors to ensure that cleanup code that logs to stderr runs to completion if the other side of stderr has been closed unexpectedly. */ } } Logger * makeSimpleLogger(bool printBuildLogs) { return new SimpleLogger(printBuildLogs); } std::atomic<uint64_t> nextId{0}; static uint64_t getPid() { #ifndef _WIN32 return getpid(); #else return GetCurrentProcessId(); #endif } Activity::Activity(Logger & logger, Verbosity lvl, ActivityType type, const std::string & s, const Logger::Fields & fields, ActivityId parent) : logger(logger), id(nextId++ + (((uint64_t) getPid()) << 32)) { logger.startActivity(id, lvl, type, s, fields, parent); } void to_json(nlohmann::json & json, std::shared_ptr<Pos> pos) { if (pos) { json["line"] = pos->line; json["column"] = pos->column; std::ostringstream str; pos->print(str, true); json["file"] = str.str(); } else { json["line"] = nullptr; json["column"] = nullptr; json["file"] = nullptr; } } struct JSONLogger : Logger { Logger & prevLogger; JSONLogger(Logger & prevLogger) : prevLogger(prevLogger) { } bool isVerbose() override { return true; } void addFields(nlohmann::json & json, const Fields & fields) { if (fields.empty()) return; auto & arr = json["fields"] = nlohmann::json::array(); for (auto & f : fields) if (f.type == Logger::Field::tInt) arr.push_back(f.i); else if (f.type == Logger::Field::tString) arr.push_back(f.s); else unreachable(); } void write(const nlohmann::json & json) { prevLogger.log(lvlError, "@nix " + json.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace)); } void log(Verbosity lvl, std::string_view s) override { nlohmann::json json; json["action"] = "msg"; json["level"] = lvl; json["msg"] = s; write(json); } void logEI(const ErrorInfo & ei) override { std::ostringstream oss; showErrorInfo(oss, ei, loggerSettings.showTrace.get()); nlohmann::json json; json["action"] = "msg"; json["level"] = ei.level; json["msg"] = oss.str(); json["raw_msg"] = ei.msg.str(); to_json(json, ei.pos); if (loggerSettings.showTrace.get() && !ei.traces.empty()) { nlohmann::json traces = nlohmann::json::array(); for (auto iter = ei.traces.rbegin(); iter != ei.traces.rend(); ++iter) { nlohmann::json stackFrame; stackFrame["raw_msg"] = iter->hint.str(); to_json(stackFrame, iter->pos); traces.push_back(stackFrame); } json["trace"] = traces; } write(json); } void startActivity(ActivityId act, Verbosity lvl, ActivityType type, const std::string & s, const Fields & fields, ActivityId parent) override { nlohmann::json json; json["action"] = "start"; json["id"] = act; json["level"] = lvl; json["type"] = type; json["text"] = s; json["parent"] = parent; addFields(json, fields); write(json); } void stopActivity(ActivityId act) override { nlohmann::json json; json["action"] = "stop"; json["id"] = act; write(json); } void result(ActivityId act, ResultType type, const Fields & fields) override { nlohmann::json json; json["action"] = "result"; json["id"] = act; json["type"] = type; addFields(json, fields); write(json); } }; Logger * makeJSONLogger(Logger & prevLogger) { return new JSONLogger(prevLogger); } static Logger::Fields getFields(nlohmann::json & json) { Logger::Fields fields; for (auto & f : json) { if (f.type() == nlohmann::json::value_t::number_unsigned) fields.emplace_back(Logger::Field(f.get<uint64_t>())); else if (f.type() == nlohmann::json::value_t::string) fields.emplace_back(Logger::Field(f.get<std::string>())); else throw Error("unsupported JSON type %d", (int) f.type()); } return fields; } std::optional<nlohmann::json> parseJSONMessage(const std::string & msg) { if (!hasPrefix(msg, "@nix ")) return std::nullopt; try { return nlohmann::json::parse(std::string(msg, 5)); } catch (std::exception & e) { printError("bad JSON log message from builder: %s", e.what()); } return std::nullopt; } bool handleJSONLogMessage(nlohmann::json & json, const Activity & act, std::map<ActivityId, Activity> & activities, bool trusted) { std::string action = json["action"]; if (action == "start") { auto type = (ActivityType) json["type"]; if (trusted || type == actFileTransfer) activities.emplace(std::piecewise_construct, std::forward_as_tuple(json["id"]), std::forward_as_tuple(*logger, (Verbosity) json["level"], type, json["text"], getFields(json["fields"]), act.id)); } else if (action == "stop") activities.erase((ActivityId) json["id"]); else if (action == "result") { auto i = activities.find((ActivityId) json["id"]); if (i != activities.end()) i->second.result((ResultType) json["type"], getFields(json["fields"])); } else if (action == "setPhase") { std::string phase = json["phase"]; act.result(resSetPhase, phase); } else if (action == "msg") { std::string msg = json["msg"]; logger->log((Verbosity) json["level"], msg); } return true; } bool handleJSONLogMessage(const std::string & msg, const Activity & act, std::map<ActivityId, Activity> & activities, bool trusted) { auto json = parseJSONMessage(msg); if (!json) return false; return handleJSONLogMessage(*json, act, activities, trusted); } Activity::~Activity() { try { logger.stopActivity(id); } catch (...) { ignoreExceptionInDestructor(); } } }
9,335
C++
.cc
293
25.245734
115
0.60049
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
10,871
references.cc
NixOS_nix/src/libutil/references.cc
#include "references.hh" #include "hash.hh" #include "archive.hh" #include <map> #include <cstdlib> #include <mutex> #include <algorithm> namespace nix { static size_t refLength = 32; /* characters */ static void search( std::string_view s, StringSet & hashes, StringSet & seen) { static std::once_flag initialised; static bool isBase32[256]; std::call_once(initialised, [](){ for (unsigned int i = 0; i < 256; ++i) isBase32[i] = false; for (unsigned int i = 0; i < nix32Chars.size(); ++i) isBase32[(unsigned char) nix32Chars[i]] = true; }); for (size_t i = 0; i + refLength <= s.size(); ) { int j; bool match = true; for (j = refLength - 1; j >= 0; --j) if (!isBase32[(unsigned char) s[i + j]]) { i += j + 1; match = false; break; } if (!match) continue; std::string ref(s.substr(i, refLength)); if (hashes.erase(ref)) { debug("found reference to '%1%' at offset '%2%'", ref, i); seen.insert(ref); } ++i; } } void RefScanSink::operator () (std::string_view data) { /* It's possible that a reference spans the previous and current fragment, so search in the concatenation of the tail of the previous fragment and the start of the current fragment. */ auto s = tail; auto tailLen = std::min(data.size(), refLength); s.append(data.data(), tailLen); search(s, hashes, seen); search(data, hashes, seen); auto rest = refLength - tailLen; if (rest < tail.size()) tail = tail.substr(tail.size() - rest); tail.append(data.data() + data.size() - tailLen, tailLen); } RewritingSink::RewritingSink(const std::string & from, const std::string & to, Sink & nextSink) : RewritingSink({{from, to}}, nextSink) { } RewritingSink::RewritingSink(const StringMap & rewrites, Sink & nextSink) : rewrites(rewrites), nextSink(nextSink) { std::string::size_type maxRewriteSize = 0; for (auto & [from, to] : rewrites) { assert(from.size() == to.size()); maxRewriteSize = std::max(maxRewriteSize, from.size()); } this->maxRewriteSize = maxRewriteSize; } void RewritingSink::operator () (std::string_view data) { std::string s(prev); s.append(data); s = rewriteStrings(s, rewrites); prev = s.size() < maxRewriteSize ? s : maxRewriteSize == 0 ? "" : std::string(s, s.size() - maxRewriteSize + 1, maxRewriteSize - 1); auto consumed = s.size() - prev.size(); pos += consumed; if (consumed) nextSink(s.substr(0, consumed)); } void RewritingSink::flush() { if (prev.empty()) return; pos += prev.size(); nextSink(prev); prev.clear(); } HashModuloSink::HashModuloSink(HashAlgorithm ha, const std::string & modulus) : hashSink(ha) , rewritingSink(modulus, std::string(modulus.size(), 0), hashSink) { } void HashModuloSink::operator () (std::string_view data) { rewritingSink(data); } HashResult HashModuloSink::finish() { rewritingSink.flush(); /* Hash the positions of the self-references. This ensures that a NAR with self-references and a NAR with some of the self-references already zeroed out do not produce a hash collision. FIXME: proof. */ for (auto & pos : rewritingSink.matches) hashSink(fmt("|%d", pos)); auto h = hashSink.finish(); return {h.first, rewritingSink.pos}; } }
3,545
C++
.cc
111
26.477477
95
0.620376
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,872
source-path.cc
NixOS_nix/src/libutil/source-path.cc
#include "source-path.hh" namespace nix { std::string_view SourcePath::baseName() const { return path.baseName().value_or("source"); } SourcePath SourcePath::parent() const { auto p = path.parent(); assert(p); return {accessor, std::move(*p)}; } std::string SourcePath::readFile() const { return accessor->readFile(path); } bool SourcePath::pathExists() const { return accessor->pathExists(path); } SourceAccessor::Stat SourcePath::lstat() const { return accessor->lstat(path); } std::optional<SourceAccessor::Stat> SourcePath::maybeLstat() const { return accessor->maybeLstat(path); } SourceAccessor::DirEntries SourcePath::readDirectory() const { return accessor->readDirectory(path); } std::string SourcePath::readLink() const { return accessor->readLink(path); } void SourcePath::dumpPath( Sink & sink, PathFilter & filter) const { return accessor->dumpPath(path, sink, filter); } std::optional<std::filesystem::path> SourcePath::getPhysicalPath() const { return accessor->getPhysicalPath(path); } std::string SourcePath::to_string() const { return accessor->showPath(path); } SourcePath SourcePath::operator / (const CanonPath & x) const { return {accessor, path / x}; } SourcePath SourcePath::operator / (std::string_view c) const { return {accessor, path / c}; } bool SourcePath::operator==(const SourcePath & x) const noexcept { return std::tie(*accessor, path) == std::tie(*x.accessor, x.path); } std::strong_ordering SourcePath::operator<=>(const SourcePath & x) const noexcept { return std::tie(*accessor, path) <=> std::tie(*x.accessor, x.path); } std::ostream & operator<<(std::ostream & str, const SourcePath & path) { str << path.to_string(); return str; } }
1,728
C++
.cc
48
33.875
81
0.732852
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,873
current-process.cc
NixOS_nix/src/libutil/current-process.cc
#include <algorithm> #include <cstring> #include "current-process.hh" #include "util.hh" #include "finally.hh" #include "file-system.hh" #include "processes.hh" #include "signals.hh" #include <math.h> #ifdef __APPLE__ # include <mach-o/dyld.h> #endif #if __linux__ # include <mutex> # include "cgroup.hh" # include "namespaces.hh" #endif #ifndef _WIN32 # include <sys/resource.h> #endif namespace nix { unsigned int getMaxCPU() { #if __linux__ try { auto cgroupFS = getCgroupFS(); if (!cgroupFS) return 0; auto cpuFile = *cgroupFS + "/" + getCurrentCgroup() + "/cpu.max"; auto cpuMax = readFile(cpuFile); auto cpuMaxParts = tokenizeString<std::vector<std::string>>(cpuMax, " \n"); if (cpuMaxParts.size() != 2) { return 0; } auto quota = cpuMaxParts[0]; auto period = cpuMaxParts[1]; if (quota != "max") return std::ceil(std::stoi(quota) / std::stof(period)); } catch (Error &) { ignoreExceptionInDestructor(lvlDebug); } #endif return 0; } ////////////////////////////////////////////////////////////////////// size_t savedStackSize = 0; void setStackSize(size_t stackSize) { #ifndef _WIN32 struct rlimit limit; if (getrlimit(RLIMIT_STACK, &limit) == 0 && limit.rlim_cur < stackSize) { savedStackSize = limit.rlim_cur; limit.rlim_cur = std::min(static_cast<rlim_t>(stackSize), limit.rlim_max); if (setrlimit(RLIMIT_STACK, &limit) != 0) { logger->log( lvlError, HintFmt( "Failed to increase stack size from %1% to %2% (maximum allowed stack size: %3%): %4%", savedStackSize, stackSize, limit.rlim_max, std::strerror(errno) ).str() ); } } #else ULONG_PTR stackLow, stackHigh; GetCurrentThreadStackLimits(&stackLow, &stackHigh); ULONG maxStackSize = stackHigh - stackLow; ULONG currStackSize = 0; // This retrieves the current promised stack size SetThreadStackGuarantee(&currStackSize); if (currStackSize < stackSize) { savedStackSize = currStackSize; ULONG newStackSize = std::min(static_cast<ULONG>(stackSize), maxStackSize); if (SetThreadStackGuarantee(&newStackSize) == 0) { logger->log( lvlError, HintFmt( "Failed to increase stack size from %1% to %2% (maximum allowed stack size: %3%): %4%", savedStackSize, stackSize, maxStackSize, std::to_string(GetLastError()) ).str() ); } } #endif } void restoreProcessContext(bool restoreMounts) { #ifndef _WIN32 unix::restoreSignals(); #endif if (restoreMounts) { #if __linux__ restoreMountNamespace(); #endif } #ifndef _WIN32 if (savedStackSize) { struct rlimit limit; if (getrlimit(RLIMIT_STACK, &limit) == 0) { limit.rlim_cur = savedStackSize; setrlimit(RLIMIT_STACK, &limit); } } #endif } ////////////////////////////////////////////////////////////////////// std::optional<Path> getSelfExe() { static auto cached = []() -> std::optional<Path> { #if __linux__ || __GNU__ return readLink("/proc/self/exe"); #elif __APPLE__ char buf[1024]; uint32_t size = sizeof(buf); if (_NSGetExecutablePath(buf, &size) == 0) return buf; else return std::nullopt; #else return std::nullopt; #endif }(); return cached; } }
3,797
C++
.cc
129
21.899225
107
0.547051
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,874
source-accessor.cc
NixOS_nix/src/libutil/source-accessor.cc
#include "source-accessor.hh" #include "archive.hh" namespace nix { static std::atomic<size_t> nextNumber{0}; SourceAccessor::SourceAccessor() : number(++nextNumber) , displayPrefix{"«unknown»"} { } bool SourceAccessor::pathExists(const CanonPath & path) { return maybeLstat(path).has_value(); } std::string SourceAccessor::readFile(const CanonPath & path) { StringSink sink; std::optional<uint64_t> size; readFile(path, sink, [&](uint64_t _size) { size = _size; }); assert(size && *size == sink.s.size()); return std::move(sink.s); } void SourceAccessor::readFile( const CanonPath & path, Sink & sink, std::function<void(uint64_t)> sizeCallback) { auto s = readFile(path); sizeCallback(s.size()); sink(s); } Hash SourceAccessor::hashPath( const CanonPath & path, PathFilter & filter, HashAlgorithm ha) { HashSink sink(ha); dumpPath(path, sink, filter); return sink.finish().first; } SourceAccessor::Stat SourceAccessor::lstat(const CanonPath & path) { if (auto st = maybeLstat(path)) return *st; else throw FileNotFound("path '%s' does not exist", showPath(path)); } void SourceAccessor::setPathDisplay(std::string displayPrefix, std::string displaySuffix) { this->displayPrefix = std::move(displayPrefix); this->displaySuffix = std::move(displaySuffix); } std::string SourceAccessor::showPath(const CanonPath & path) { return displayPrefix + path.abs() + displaySuffix; } CanonPath SourceAccessor::resolveSymlinks( const CanonPath & path, SymlinkResolution mode) { auto res = CanonPath::root; int linksAllowed = 1024; std::list<std::string> todo; for (auto & c : path) todo.push_back(std::string(c)); while (!todo.empty()) { auto c = *todo.begin(); todo.pop_front(); if (c == "" || c == ".") ; else if (c == "..") res.pop(); else { res.push(c); if (mode == SymlinkResolution::Full || !todo.empty()) { if (auto st = maybeLstat(res); st && st->type == SourceAccessor::tSymlink) { if (!linksAllowed--) throw Error("infinite symlink recursion in path '%s'", showPath(path)); auto target = readLink(res); res.pop(); if (hasPrefix(target, "/")) res = CanonPath::root; todo.splice(todo.begin(), tokenizeString<std::list<std::string>>(target, "/")); } } } } return res; } }
2,650
C++
.cc
92
22.565217
99
0.601575
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,875
git.cc
NixOS_nix/src/libutil/git.cc
#include <cerrno> #include <algorithm> #include <vector> #include <map> #include <regex> #include <strings.h> // for strcasecmp #include "signals.hh" #include "config.hh" #include "hash.hh" #include "git.hh" #include "serialise.hh" namespace nix::git { using namespace nix; using namespace std::string_literals; std::optional<Mode> decodeMode(RawMode m) { switch (m) { case (RawMode) Mode::Directory: case (RawMode) Mode::Executable: case (RawMode) Mode::Regular: case (RawMode) Mode::Symlink: return (Mode) m; default: return std::nullopt; } } static std::string getStringUntil(Source & source, char byte) { std::string s; char n[1]; source(std::string_view { n, 1 }); while (*n != byte) { s += *n; source(std::string_view { n, 1 }); } return s; } static std::string getString(Source & source, int n) { std::string v; v.resize(n); source(v); return v; } void parseBlob( FileSystemObjectSink & sink, const CanonPath & sinkPath, Source & source, BlobMode blobMode, const ExperimentalFeatureSettings & xpSettings) { xpSettings.require(Xp::GitHashing); unsigned long long size = std::stoi(getStringUntil(source, 0)); auto doRegularFile = [&](bool executable) { sink.createRegularFile(sinkPath, [&](auto & crf) { if (executable) crf.isExecutable(); crf.preallocateContents(size); unsigned long long left = size; std::string buf; buf.reserve(65536); while (left) { checkInterrupt(); buf.resize(std::min((unsigned long long)buf.capacity(), left)); source(buf); crf(buf); left -= buf.size(); } }); }; switch (blobMode) { case BlobMode::Regular: doRegularFile(false); break; case BlobMode::Executable: doRegularFile(true); break; case BlobMode::Symlink: { std::string target; target.resize(size, '0'); target.reserve(size); for (size_t n = 0; n < target.size();) { checkInterrupt(); n += source.read( const_cast<char *>(target.c_str()) + n, target.size() - n); } sink.createSymlink(sinkPath, target); break; } default: assert(false); } } void parseTree( FileSystemObjectSink & sink, const CanonPath & sinkPath, Source & source, std::function<SinkHook> hook, const ExperimentalFeatureSettings & xpSettings) { unsigned long long size = std::stoi(getStringUntil(source, 0)); unsigned long long left = size; sink.createDirectory(sinkPath); while (left) { std::string perms = getStringUntil(source, ' '); left -= perms.size(); left -= 1; RawMode rawMode = std::stoi(perms, 0, 8); auto modeOpt = decodeMode(rawMode); if (!modeOpt) throw Error("Unknown Git permission: %o", perms); auto mode = std::move(*modeOpt); std::string name = getStringUntil(source, '\0'); left -= name.size(); left -= 1; std::string hashs = getString(source, 20); left -= 20; Hash hash(HashAlgorithm::SHA1); std::copy(hashs.begin(), hashs.end(), hash.hash); hook(CanonPath{name}, TreeEntry { .mode = mode, .hash = hash, }); } } ObjectType parseObjectType( Source & source, const ExperimentalFeatureSettings & xpSettings) { xpSettings.require(Xp::GitHashing); auto type = getString(source, 5); if (type == "blob ") { return ObjectType::Blob; } else if (type == "tree ") { return ObjectType::Tree; } else throw Error("input doesn't look like a Git object"); } void parse( FileSystemObjectSink & sink, const CanonPath & sinkPath, Source & source, BlobMode rootModeIfBlob, std::function<SinkHook> hook, const ExperimentalFeatureSettings & xpSettings) { xpSettings.require(Xp::GitHashing); auto type = parseObjectType(source, xpSettings); switch (type) { case ObjectType::Blob: parseBlob(sink, sinkPath, source, rootModeIfBlob, xpSettings); break; case ObjectType::Tree: parseTree(sink, sinkPath, source, hook, xpSettings); break; default: assert(false); }; } std::optional<Mode> convertMode(SourceAccessor::Type type) { switch (type) { case SourceAccessor::tSymlink: return Mode::Symlink; case SourceAccessor::tRegular: return Mode::Regular; case SourceAccessor::tDirectory: return Mode::Directory; case SourceAccessor::tMisc: return std::nullopt; default: unreachable(); } } void restore(FileSystemObjectSink & sink, Source & source, std::function<RestoreHook> hook) { parse(sink, CanonPath::root, source, BlobMode::Regular, [&](CanonPath name, TreeEntry entry) { auto [accessor, from] = hook(entry.hash); auto stat = accessor->lstat(from); auto gotOpt = convertMode(stat.type); if (!gotOpt) throw Error("file '%s' (git hash %s) has an unsupported type", from, entry.hash.to_string(HashFormat::Base16, false)); auto & got = *gotOpt; if (got != entry.mode) throw Error("git mode of file '%s' (git hash %s) is %o but expected %o", from, entry.hash.to_string(HashFormat::Base16, false), (RawMode) got, (RawMode) entry.mode); copyRecursive( *accessor, from, sink, name); }); } void dumpBlobPrefix( uint64_t size, Sink & sink, const ExperimentalFeatureSettings & xpSettings) { xpSettings.require(Xp::GitHashing); auto s = fmt("blob %d\0"s, std::to_string(size)); sink(s); } void dumpTree(const Tree & entries, Sink & sink, const ExperimentalFeatureSettings & xpSettings) { xpSettings.require(Xp::GitHashing); std::string v1; for (auto & [name, entry] : entries) { auto name2 = name; if (entry.mode == Mode::Directory) { assert(!name2.empty()); assert(name2.back() == '/'); name2.pop_back(); } v1 += fmt("%o %s\0"s, static_cast<RawMode>(entry.mode), name2); std::copy(entry.hash.hash, entry.hash.hash + entry.hash.hashSize, std::back_inserter(v1)); } { auto s = fmt("tree %d\0"s, v1.size()); sink(s); } sink(v1); } Mode dump( const SourcePath & path, Sink & sink, std::function<DumpHook> hook, PathFilter & filter, const ExperimentalFeatureSettings & xpSettings) { auto st = path.lstat(); switch (st.type) { case SourceAccessor::tRegular: { path.readFile(sink, [&](uint64_t size) { dumpBlobPrefix(size, sink, xpSettings); }); return st.isExecutable ? Mode::Executable : Mode::Regular; } case SourceAccessor::tDirectory: { Tree entries; for (auto & [name, _] : path.readDirectory()) { auto child = path / name; if (!filter(child.path.abs())) continue; auto entry = hook(child); auto name2 = name; if (entry.mode == Mode::Directory) name2 += "/"; entries.insert_or_assign(std::move(name2), std::move(entry)); } dumpTree(entries, sink, xpSettings); return Mode::Directory; } case SourceAccessor::tSymlink: { auto target = path.readLink(); dumpBlobPrefix(target.size(), sink, xpSettings); sink(target); return Mode::Symlink; } case SourceAccessor::tMisc: default: throw Error("file '%1%' has an unsupported type", path); } } TreeEntry dumpHash( HashAlgorithm ha, const SourcePath & path, PathFilter & filter) { std::function<DumpHook> hook; hook = [&](const SourcePath & path) -> TreeEntry { auto hashSink = HashSink(ha); auto mode = dump(path, hashSink, hook, filter); auto hash = hashSink.finish().first; return { .mode = mode, .hash = hash, }; }; return hook(path); } std::optional<LsRemoteRefLine> parseLsRemoteLine(std::string_view line) { const static std::regex line_regex("^(ref: *)?([^\\s]+)(?:\\t+(.*))?$"); std::match_results<std::string_view::const_iterator> match; if (!std::regex_match(line.cbegin(), line.cend(), match, line_regex)) return std::nullopt; return LsRemoteRefLine { .kind = match[1].length() == 0 ? LsRemoteRefLine::Kind::Object : LsRemoteRefLine::Kind::Symbolic, .target = match[2], .reference = match[3].length() == 0 ? std::nullopt : std::optional<std::string>{ match[3] } }; } }
9,066
C++
.cc
297
23.468013
99
0.593958
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,876
xml-writer.cc
NixOS_nix/src/libutil/xml-writer.cc
#include <cassert> #include "xml-writer.hh" namespace nix { XMLWriter::XMLWriter(bool indent, std::ostream & output) : output(output), indent(indent) { output << "<?xml version='1.0' encoding='utf-8'?>" << std::endl; closed = false; } XMLWriter::~XMLWriter() { close(); } void XMLWriter::close() { if (closed) return; while (!pendingElems.empty()) closeElement(); closed = true; } void XMLWriter::indent_(size_t depth) { if (!indent) return; output << std::string(depth * 2, ' '); } void XMLWriter::openElement( std::string_view name, const XMLAttrs & attrs) { assert(!closed); indent_(pendingElems.size()); output << "<" << name; writeAttrs(attrs); output << ">"; if (indent) output << std::endl; pendingElems.push_back(std::string(name)); } void XMLWriter::closeElement() { assert(!pendingElems.empty()); indent_(pendingElems.size() - 1); output << "</" << pendingElems.back() << ">"; if (indent) output << std::endl; pendingElems.pop_back(); if (pendingElems.empty()) closed = true; } void XMLWriter::writeEmptyElement( std::string_view name, const XMLAttrs & attrs) { assert(!closed); indent_(pendingElems.size()); output << "<" << name; writeAttrs(attrs); output << " />"; if (indent) output << std::endl; } void XMLWriter::writeAttrs(const XMLAttrs & attrs) { for (auto & i : attrs) { output << " " << i.first << "=\""; for (size_t j = 0; j < i.second.size(); ++j) { char c = i.second[j]; if (c == '"') output << "&quot;"; else if (c == '<') output << "&lt;"; else if (c == '>') output << "&gt;"; else if (c == '&') output << "&amp;"; /* Escape newlines to prevent attribute normalisation (see XML spec, section 3.3.3. */ else if (c == '\n') output << "&#xA;"; else output << c; } output << "\""; } } }
2,009
C++
.cc
75
21.786667
70
0.560899
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,877
file-descriptor.cc
NixOS_nix/src/libutil/file-descriptor.cc
#include "file-system.hh" #include "signals.hh" #include "finally.hh" #include "serialise.hh" #include "util.hh" #include <fcntl.h> #include <unistd.h> #ifdef _WIN32 # include <winnt.h> # include <fileapi.h> # include "windows-error.hh" #endif namespace nix { void writeLine(Descriptor fd, std::string s) { s += '\n'; writeFull(fd, s); } std::string drainFD(Descriptor fd, bool block, const size_t reserveSize) { // the parser needs two extra bytes to append terminating characters, other users will // not care very much about the extra memory. StringSink sink(reserveSize + 2); #ifdef _WIN32 // non-blocking is not supported this way on Windows assert(block); drainFD(fd, sink); #else drainFD(fd, sink, block); #endif return std::move(sink.s); } ////////////////////////////////////////////////////////////////////// AutoCloseFD::AutoCloseFD() : fd{INVALID_DESCRIPTOR} {} AutoCloseFD::AutoCloseFD(Descriptor fd) : fd{fd} {} // NOTE: This can be noexcept since we are just copying a value and resetting // the file descriptor in the rhs. AutoCloseFD::AutoCloseFD(AutoCloseFD && that) noexcept : fd{that.fd} { that.fd = INVALID_DESCRIPTOR; } AutoCloseFD & AutoCloseFD::operator =(AutoCloseFD && that) { close(); fd = that.fd; that.fd = INVALID_DESCRIPTOR; return *this; } AutoCloseFD::~AutoCloseFD() { try { close(); } catch (...) { ignoreExceptionInDestructor(); } } Descriptor AutoCloseFD::get() const { return fd; } void AutoCloseFD::close() { if (fd != INVALID_DESCRIPTOR) { if( #ifdef _WIN32 ::CloseHandle(fd) #else ::close(fd) #endif == -1) /* This should never happen. */ throw NativeSysError("closing file descriptor %1%", fd); fd = INVALID_DESCRIPTOR; } } void AutoCloseFD::fsync() const { if (fd != INVALID_DESCRIPTOR) { int result; result = #ifdef _WIN32 ::FlushFileBuffers(fd) #elif __APPLE__ ::fcntl(fd, F_FULLFSYNC) #else ::fsync(fd) #endif ; if (result == -1) throw NativeSysError("fsync file descriptor %1%", fd); } } void AutoCloseFD::startFsync() const { #if __linux__ if (fd != -1) { /* Ignore failure, since fsync must be run later anyway. This is just a performance optimization. */ ::sync_file_range(fd, 0, 0, SYNC_FILE_RANGE_WRITE); } #endif } AutoCloseFD::operator bool() const { return fd != INVALID_DESCRIPTOR; } Descriptor AutoCloseFD::release() { Descriptor oldFD = fd; fd = INVALID_DESCRIPTOR; return oldFD; } ////////////////////////////////////////////////////////////////////// void Pipe::close() { readSide.close(); writeSide.close(); } }
2,834
C++
.cc
118
19.949153
112
0.613492
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,878
archive.cc
NixOS_nix/src/libutil/archive.cc
#include <cerrno> #include <algorithm> #include <vector> #include <map> #include <strings.h> // for strcasecmp #include "archive.hh" #include "config-global.hh" #include "posix-source-accessor.hh" #include "source-path.hh" #include "file-system.hh" #include "signals.hh" namespace nix { struct ArchiveSettings : Config { Setting<bool> useCaseHack{this, #if __APPLE__ true, #else false, #endif "use-case-hack", "Whether to enable a macOS-specific hack for dealing with file name case collisions."}; }; static ArchiveSettings archiveSettings; static GlobalConfig::Register rArchiveSettings(&archiveSettings); PathFilter defaultPathFilter = [](const Path &) { return true; }; void SourceAccessor::dumpPath( const CanonPath & path, Sink & sink, PathFilter & filter) { auto dumpContents = [&](const CanonPath & path) { sink << "contents"; std::optional<uint64_t> size; readFile(path, sink, [&](uint64_t _size) { size = _size; sink << _size; }); assert(size); writePadding(*size, sink); }; std::function<void(const CanonPath & path)> dump; dump = [&](const CanonPath & path) { checkInterrupt(); auto st = lstat(path); sink << "("; if (st.type == tRegular) { sink << "type" << "regular"; if (st.isExecutable) sink << "executable" << ""; dumpContents(path); } else if (st.type == tDirectory) { sink << "type" << "directory"; /* If we're on a case-insensitive system like macOS, undo the case hack applied by restorePath(). */ std::map<std::string, std::string> unhacked; for (auto & i : readDirectory(path)) if (archiveSettings.useCaseHack) { std::string name(i.first); size_t pos = i.first.find(caseHackSuffix); if (pos != std::string::npos) { debug("removing case hack suffix from '%s'", path / i.first); name.erase(pos); } if (!unhacked.emplace(name, i.first).second) throw Error("file name collision between '%s' and '%s'", (path / unhacked[name]), (path / i.first)); } else unhacked.emplace(i.first, i.first); for (auto & i : unhacked) if (filter((path / i.first).abs())) { sink << "entry" << "(" << "name" << i.first << "node"; dump(path / i.second); sink << ")"; } } else if (st.type == tSymlink) sink << "type" << "symlink" << "target" << readLink(path); else throw Error("file '%s' has an unsupported type", path); sink << ")"; }; sink << narVersionMagic1; dump(path); } time_t dumpPathAndGetMtime(const Path & path, Sink & sink, PathFilter & filter) { auto path2 = PosixSourceAccessor::createAtRoot(path); path2.dumpPath(sink, filter); return path2.accessor.dynamic_pointer_cast<PosixSourceAccessor>()->mtime; } void dumpPath(const Path & path, Sink & sink, PathFilter & filter) { dumpPathAndGetMtime(path, sink, filter); } void dumpString(std::string_view s, Sink & sink) { sink << narVersionMagic1 << "(" << "type" << "regular" << "contents" << s << ")"; } template<typename... Args> static SerialisationError badArchive(std::string_view s, const Args & ... args) { return SerialisationError("bad archive: " + s, args...); } static void parseContents(CreateRegularFileSink & sink, Source & source) { uint64_t size = readLongLong(source); sink.preallocateContents(size); uint64_t left = size; std::array<char, 65536> buf; while (left) { checkInterrupt(); auto n = buf.size(); if ((uint64_t)n > left) n = left; source(buf.data(), n); sink({buf.data(), n}); left -= n; } readPadding(size, source); } struct CaseInsensitiveCompare { bool operator() (const std::string & a, const std::string & b) const { return strcasecmp(a.c_str(), b.c_str()) < 0; } }; static void parse(FileSystemObjectSink & sink, Source & source, const CanonPath & path) { auto getString = [&]() { checkInterrupt(); return readString(source); }; auto expectTag = [&](std::string_view expected) { auto tag = getString(); if (tag != expected) throw badArchive("expected tag '%s', got '%s'", expected, tag); }; expectTag("("); expectTag("type"); auto type = getString(); if (type == "regular") { sink.createRegularFile(path, [&](auto & crf) { auto tag = getString(); if (tag == "executable") { auto s2 = getString(); if (s2 != "") throw badArchive("executable marker has non-empty value"); crf.isExecutable(); tag = getString(); } if (tag == "contents") parseContents(crf, source); expectTag(")"); }); } else if (type == "directory") { sink.createDirectory(path); std::map<Path, int, CaseInsensitiveCompare> names; std::string prevName; while (1) { auto tag = getString(); if (tag == ")") break; if (tag != "entry") throw badArchive("expected tag 'entry' or ')', got '%s'", tag); expectTag("("); expectTag("name"); auto name = getString(); if (name.empty() || name == "." || name == ".." || name.find('/') != std::string::npos || name.find((char) 0) != std::string::npos) throw badArchive("NAR contains invalid file name '%1%'", name); if (name <= prevName) throw badArchive("NAR directory is not sorted"); prevName = name; if (archiveSettings.useCaseHack) { auto i = names.find(name); if (i != names.end()) { debug("case collision between '%1%' and '%2%'", i->first, name); name += caseHackSuffix; name += std::to_string(++i->second); auto j = names.find(name); if (j != names.end()) throw badArchive("NAR contains file name '%s' that collides with case-hacked file name '%s'", prevName, j->first); } else names[name] = 0; } expectTag("node"); parse(sink, source, path / name); expectTag(")"); } } else if (type == "symlink") { expectTag("target"); auto target = getString(); sink.createSymlink(path, target); expectTag(")"); } else throw badArchive("unknown file type '%s'", type); } void parseDump(FileSystemObjectSink & sink, Source & source) { std::string version; try { version = readString(source, narVersionMagic1.size()); } catch (SerialisationError & e) { /* This generally means the integer at the start couldn't be decoded. Ignore and throw the exception below. */ } if (version != narVersionMagic1) throw badArchive("input doesn't look like a Nix archive"); parse(sink, source, CanonPath::root); } void restorePath(const std::filesystem::path & path, Source & source, bool startFsync) { RestoreSink sink{startFsync}; sink.dstPath = path; parseDump(sink, source); } void copyNAR(Source & source, Sink & sink) { // FIXME: if 'source' is the output of dumpPath() followed by EOF, // we should just forward all data directly without parsing. NullFileSystemObjectSink parseSink; /* just parse the NAR */ TeeSource wrapper { source, sink }; parseDump(parseSink, wrapper); } }
8,155
C++
.cc
228
26.859649
143
0.553094
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,879
fs-sink.cc
NixOS_nix/src/libutil/fs-sink.cc
#include <fcntl.h> #include "error.hh" #include "config-global.hh" #include "fs-sink.hh" #if _WIN32 # include <fileapi.h> # include "file-path.hh" # include "windows-error.hh" #endif namespace nix { void copyRecursive( SourceAccessor & accessor, const CanonPath & from, FileSystemObjectSink & sink, const CanonPath & to) { auto stat = accessor.lstat(from); switch (stat.type) { case SourceAccessor::tSymlink: { sink.createSymlink(to, accessor.readLink(from)); break; } case SourceAccessor::tRegular: { sink.createRegularFile(to, [&](CreateRegularFileSink & crf) { if (stat.isExecutable) crf.isExecutable(); accessor.readFile(from, crf, [&](uint64_t size) { crf.preallocateContents(size); }); }); break; } case SourceAccessor::tDirectory: { sink.createDirectory(to); for (auto & [name, _] : accessor.readDirectory(from)) { copyRecursive( accessor, from / name, sink, to / name); break; } break; } case SourceAccessor::tMisc: throw Error("file '%1%' has an unsupported type", from); default: unreachable(); } } struct RestoreSinkSettings : Config { Setting<bool> preallocateContents{this, false, "preallocate-contents", "Whether to preallocate files when writing objects with known size."}; }; static RestoreSinkSettings restoreSinkSettings; static GlobalConfig::Register r1(&restoreSinkSettings); static std::filesystem::path append(const std::filesystem::path & src, const CanonPath & path) { auto dst = src; if (!path.rel().empty()) dst /= path.rel(); return dst; } void RestoreSink::createDirectory(const CanonPath & path) { auto p = append(dstPath, path); if (!std::filesystem::create_directory(p)) throw Error("path '%s' already exists", p.string()); }; struct RestoreRegularFile : CreateRegularFileSink { AutoCloseFD fd; bool startFsync = false; ~RestoreRegularFile() { /* Initiate an fsync operation without waiting for the result. The real fsync should be run before registering a store path, but this is a performance optimization to allow the disk write to start early. */ if (fd && startFsync) fd.startFsync(); } void operator () (std::string_view data) override; void isExecutable() override; void preallocateContents(uint64_t size) override; }; void RestoreSink::createRegularFile(const CanonPath & path, std::function<void(CreateRegularFileSink &)> func) { auto p = append(dstPath, path); RestoreRegularFile crf; crf.startFsync = startFsync; crf.fd = #ifdef _WIN32 CreateFileW(p.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL) #else open(p.c_str(), O_CREAT | O_EXCL | O_WRONLY | O_CLOEXEC, 0666) #endif ; if (!crf.fd) throw NativeSysError("creating file '%1%'", p); func(crf); } void RestoreRegularFile::isExecutable() { // Windows doesn't have a notion of executable file permissions we // care about here, right? #ifndef _WIN32 struct stat st; if (fstat(fd.get(), &st) == -1) throw SysError("fstat"); if (fchmod(fd.get(), st.st_mode | (S_IXUSR | S_IXGRP | S_IXOTH)) == -1) throw SysError("fchmod"); #endif } void RestoreRegularFile::preallocateContents(uint64_t len) { if (!restoreSinkSettings.preallocateContents) return; #if HAVE_POSIX_FALLOCATE if (len) { errno = posix_fallocate(fd.get(), 0, len); /* Note that EINVAL may indicate that the underlying filesystem doesn't support preallocation (e.g. on OpenSolaris). Since preallocation is just an optimisation, ignore it. */ if (errno && errno != EINVAL && errno != EOPNOTSUPP && errno != ENOSYS) throw SysError("preallocating file of %1% bytes", len); } #endif } void RestoreRegularFile::operator () (std::string_view data) { writeFull(fd.get(), data); } void RestoreSink::createSymlink(const CanonPath & path, const std::string & target) { auto p = append(dstPath, path); nix::createSymlink(target, p.string()); } void RegularFileSink::createRegularFile(const CanonPath & path, std::function<void(CreateRegularFileSink &)> func) { struct CRF : CreateRegularFileSink { RegularFileSink & back; CRF(RegularFileSink & back) : back(back) {} void operator () (std::string_view data) override { back.sink(data); } void isExecutable() override {} } crf { *this }; func(crf); } void NullFileSystemObjectSink::createRegularFile(const CanonPath & path, std::function<void(CreateRegularFileSink &)> func) { struct : CreateRegularFileSink { void operator () (std::string_view data) override {} void isExecutable() override {} } crf; // Even though `NullFileSystemObjectSink` doesn't do anything, it's important // that we call the function, to e.g. advance the parser using this // sink. func(crf); } }
5,247
C++
.cc
162
26.796296
123
0.655589
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,880
english.cc
NixOS_nix/src/libutil/english.cc
#include "english.hh" namespace nix { std::ostream & pluralize( std::ostream & output, unsigned int count, const std::string_view single, const std::string_view plural) { if (count == 1) output << "1 " << single; else output << count << " " << plural; return output; } }
318
C++
.cc
15
17.066667
41
0.603333
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,881
terminal.cc
NixOS_nix/src/libutil/terminal.cc
#include "terminal.hh" #include "environment-variables.hh" #include "sync.hh" #if _WIN32 # include <io.h> # define WIN32_LEAN_AND_MEAN # include <windows.h> # define isatty _isatty #else # include <sys/ioctl.h> #endif #include <unistd.h> namespace nix { bool isTTY() { static const bool tty = isatty(STDERR_FILENO) && getEnv("TERM").value_or("dumb") != "dumb" && !(getEnv("NO_COLOR").has_value() || getEnv("NOCOLOR").has_value()); return tty; } std::string filterANSIEscapes(std::string_view s, bool filterAll, unsigned int width) { std::string t, e; size_t w = 0; auto i = s.begin(); while (w < (size_t) width && i != s.end()) { if (*i == '\e') { std::string e; e += *i++; char last = 0; if (i != s.end() && *i == '[') { e += *i++; // eat parameter bytes while (i != s.end() && *i >= 0x30 && *i <= 0x3f) e += *i++; // eat intermediate bytes while (i != s.end() && *i >= 0x20 && *i <= 0x2f) e += *i++; // eat final byte if (i != s.end() && *i >= 0x40 && *i <= 0x7e) e += last = *i++; } else if (i != s.end() && *i == ']') { // OSC e += *i++; // eat ESC while (i != s.end() && *i != '\e') e += *i++; // eat backslash if (i != s.end() && *i == '\\') e += last = *i++; } else { if (i != s.end() && *i >= 0x40 && *i <= 0x5f) e += *i++; } if (!filterAll && last == 'm') t += e; } else if (*i == '\t') { i++; t += ' '; w++; while (w < (size_t) width && w % 8) { t += ' '; w++; } } else if (*i == '\r' || *i == '\a') // do nothing for now i++; else { w++; // Copy one UTF-8 character. if ((*i & 0xe0) == 0xc0) { t += *i++; if (i != s.end() && ((*i & 0xc0) == 0x80)) t += *i++; } else if ((*i & 0xf0) == 0xe0) { t += *i++; if (i != s.end() && ((*i & 0xc0) == 0x80)) { t += *i++; if (i != s.end() && ((*i & 0xc0) == 0x80)) t += *i++; } } else if ((*i & 0xf8) == 0xf0) { t += *i++; if (i != s.end() && ((*i & 0xc0) == 0x80)) { t += *i++; if (i != s.end() && ((*i & 0xc0) == 0x80)) { t += *i++; if (i != s.end() && ((*i & 0xc0) == 0x80)) t += *i++; } } } else t += *i++; } } return t; } ////////////////////////////////////////////////////////////////////// static Sync<std::pair<unsigned short, unsigned short>> windowSize{{0, 0}}; void updateWindowSize() { #ifndef _WIN32 struct winsize ws; if (ioctl(2, TIOCGWINSZ, &ws) == 0) { auto windowSize_(windowSize.lock()); windowSize_->first = ws.ws_row; windowSize_->second = ws.ws_col; } #else CONSOLE_SCREEN_BUFFER_INFO info; // From https://stackoverflow.com/a/12642749 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info) != 0) { auto windowSize_(windowSize.lock()); // From https://github.com/libuv/libuv/blob/v1.48.0/src/win/tty.c#L1130 windowSize_->first = info.srWindow.Bottom - info.srWindow.Top + 1; windowSize_->second = info.dwSize.X; } #endif } std::pair<unsigned short, unsigned short> getWindowSize() { return *windowSize.lock(); } }
3,811
C++
.cc
115
23.365217
85
0.401088
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,882
tarfile.cc
NixOS_nix/src/libutil/tarfile.cc
#include <archive.h> #include <archive_entry.h> #include "finally.hh" #include "serialise.hh" #include "tarfile.hh" #include "file-system.hh" namespace nix { namespace fs { using namespace std::filesystem; } namespace { int callback_open(struct archive *, void * self) { return ARCHIVE_OK; } ssize_t callback_read(struct archive * archive, void * _self, const void ** buffer) { auto self = (TarArchive *) _self; *buffer = self->buffer.data(); try { return self->source->read((char *) self->buffer.data(), self->buffer.size()); } catch (EndOfFile &) { return 0; } catch (std::exception & err) { archive_set_error(archive, EIO, "Source threw exception: %s", err.what()); return -1; } } int callback_close(struct archive *, void * self) { return ARCHIVE_OK; } void checkLibArchive(archive * archive, int err, const std::string & reason) { if (err == ARCHIVE_EOF) throw EndOfFile("reached end of archive"); else if (err != ARCHIVE_OK) throw Error(reason, archive_error_string(archive)); } constexpr auto defaultBufferSize = std::size_t{65536}; } void TarArchive::check(int err, const std::string & reason) { checkLibArchive(archive, err, reason); } /// @brief Get filter_code from its name. /// /// libarchive does not provide a convenience function like archive_write_add_filter_by_name but for reading. /// Instead it's necessary to use this kludge to convert method -> code and /// then use archive_read_support_filter_by_code. Arguably this is better than /// hand-rolling the equivalent function that is better implemented in libarchive. int getArchiveFilterCodeByName(const std::string & method) { auto * ar = archive_write_new(); auto cleanup = Finally{[&ar]() { checkLibArchive(ar, archive_write_close(ar), "failed to close archive: %s"); }}; auto err = archive_write_add_filter_by_name(ar, method.c_str()); checkLibArchive(ar, err, "failed to get libarchive filter by name: %s"); auto code = archive_filter_code(ar, 0); return code; } static void enableSupportedFormats(struct archive * archive) { archive_read_support_format_tar(archive); archive_read_support_format_zip(archive); /* Enable support for empty files so we don't throw an exception for empty HTTP 304 "Not modified" responses. See downloadTarball(). */ archive_read_support_format_empty(archive); } TarArchive::TarArchive(Source & source, bool raw, std::optional<std::string> compression_method) : archive{archive_read_new()} , source{&source} , buffer(defaultBufferSize) { if (!compression_method) { archive_read_support_filter_all(archive); } else { archive_read_support_filter_by_code(archive, getArchiveFilterCodeByName(*compression_method)); } if (!raw) enableSupportedFormats(archive); else { archive_read_support_format_raw(archive); archive_read_support_format_empty(archive); } archive_read_set_option(archive, NULL, "mac-ext", NULL); check( archive_read_open(archive, (void *) this, callback_open, callback_read, callback_close), "Failed to open archive (%s)"); } TarArchive::TarArchive(const std::filesystem::path & path) : archive{archive_read_new()} , buffer(defaultBufferSize) { archive_read_support_filter_all(archive); enableSupportedFormats(archive); archive_read_set_option(archive, NULL, "mac-ext", NULL); check(archive_read_open_filename(archive, path.string().c_str(), 16384), "failed to open archive: %s"); } void TarArchive::close() { check(archive_read_close(this->archive), "Failed to close archive (%s)"); } TarArchive::~TarArchive() { if (this->archive) archive_read_free(this->archive); } static void extract_archive(TarArchive & archive, const fs::path & destDir) { int flags = ARCHIVE_EXTRACT_TIME | ARCHIVE_EXTRACT_SECURE_SYMLINKS | ARCHIVE_EXTRACT_SECURE_NODOTDOT; for (;;) { struct archive_entry * entry; int r = archive_read_next_header(archive.archive, &entry); if (r == ARCHIVE_EOF) break; auto name = archive_entry_pathname(entry); if (!name) throw Error("cannot get archive member name: %s", archive_error_string(archive.archive)); if (r == ARCHIVE_WARN) warn(archive_error_string(archive.archive)); else archive.check(r); archive_entry_copy_pathname(entry, (destDir / name).string().c_str()); // sources can and do contain dirs with no rx bits if (archive_entry_filetype(entry) == AE_IFDIR && (archive_entry_mode(entry) & 0500) != 0500) archive_entry_set_mode(entry, archive_entry_mode(entry) | 0500); // Patch hardlink path const char * original_hardlink = archive_entry_hardlink(entry); if (original_hardlink) { archive_entry_copy_hardlink(entry, (destDir / original_hardlink).string().c_str()); } archive.check(archive_read_extract(archive.archive, entry, flags)); } archive.close(); } void unpackTarfile(Source & source, const fs::path & destDir) { auto archive = TarArchive(source); fs::create_directories(destDir); extract_archive(archive, destDir); } void unpackTarfile(const fs::path & tarFile, const fs::path & destDir) { auto archive = TarArchive(tarFile); fs::create_directories(destDir); extract_archive(archive, destDir); } time_t unpackTarfileToSink(TarArchive & archive, ExtendedFileSystemObjectSink & parseSink) { time_t lastModified = 0; for (;;) { // FIXME: merge with extract_archive struct archive_entry * entry; int r = archive_read_next_header(archive.archive, &entry); if (r == ARCHIVE_EOF) break; auto path = archive_entry_pathname(entry); if (!path) throw Error("cannot get archive member name: %s", archive_error_string(archive.archive)); auto cpath = CanonPath{path}; if (r == ARCHIVE_WARN) warn(archive_error_string(archive.archive)); else archive.check(r); lastModified = std::max(lastModified, archive_entry_mtime(entry)); if (auto target = archive_entry_hardlink(entry)) { parseSink.createHardlink(cpath, CanonPath(target)); continue; } switch (auto type = archive_entry_filetype(entry)) { case AE_IFDIR: parseSink.createDirectory(cpath); break; case AE_IFREG: { parseSink.createRegularFile(cpath, [&](auto & crf) { if (archive_entry_mode(entry) & S_IXUSR) crf.isExecutable(); while (true) { std::vector<unsigned char> buf(128 * 1024); auto n = archive_read_data(archive.archive, buf.data(), buf.size()); if (n < 0) throw Error("cannot read file '%s' from tarball", path); if (n == 0) break; crf(std::string_view{ (const char *) buf.data(), (size_t) n, }); } }); break; } case AE_IFLNK: { auto target = archive_entry_symlink(entry); parseSink.createSymlink(cpath, target); break; } default: throw Error("file '%s' in tarball has unsupported file type %d", path, type); } } return lastModified; } }
7,642
C++
.cc
205
30.404878
117
0.638209
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,883
canon-path.cc
NixOS_nix/src/libutil/canon-path.cc
#include "canon-path.hh" #include "util.hh" #include "file-path-impl.hh" #include "strings-inline.hh" namespace nix { CanonPath CanonPath::root = CanonPath("/"); static std::string absPathPure(std::string_view path) { return canonPathInner<UnixPathTrait>(path, [](auto &, auto &){}); } CanonPath::CanonPath(std::string_view raw) : path(absPathPure(concatStrings("/", raw))) { } CanonPath::CanonPath(std::string_view raw, const CanonPath & root) : path(absPathPure( raw.size() > 0 && raw[0] == '/' ? raw : concatStrings(root.abs(), "/", raw))) { } CanonPath::CanonPath(const std::vector<std::string> & elems) : path("/") { for (auto & s : elems) push(s); } std::optional<CanonPath> CanonPath::parent() const { if (isRoot()) return std::nullopt; return CanonPath(unchecked_t(), path.substr(0, std::max((size_t) 1, path.rfind('/')))); } void CanonPath::pop() { assert(!isRoot()); path.resize(std::max((size_t) 1, path.rfind('/'))); } bool CanonPath::isWithin(const CanonPath & parent) const { return !( path.size() < parent.path.size() || path.substr(0, parent.path.size()) != parent.path || (parent.path.size() > 1 && path.size() > parent.path.size() && path[parent.path.size()] != '/')); } CanonPath CanonPath::removePrefix(const CanonPath & prefix) const { assert(isWithin(prefix)); if (prefix.isRoot()) return *this; if (path.size() == prefix.path.size()) return root; return CanonPath(unchecked_t(), path.substr(prefix.path.size())); } void CanonPath::extend(const CanonPath & x) { if (x.isRoot()) return; if (isRoot()) path += x.rel(); else path += x.abs(); } CanonPath CanonPath::operator / (const CanonPath & x) const { auto res = *this; res.extend(x); return res; } void CanonPath::push(std::string_view c) { assert(c.find('/') == c.npos); assert(c != "." && c != ".."); if (!isRoot()) path += '/'; path += c; } CanonPath CanonPath::operator / (std::string_view c) const { auto res = *this; res.push(c); return res; } bool CanonPath::isAllowed(const std::set<CanonPath> & allowed) const { /* Check if `this` is an exact match or the parent of an allowed path. */ auto lb = allowed.lower_bound(*this); if (lb != allowed.end()) { if (lb->isWithin(*this)) return true; } /* Check if a parent of `this` is allowed. */ auto path = *this; while (!path.isRoot()) { path.pop(); if (allowed.count(path)) return true; } return false; } std::ostream & operator << (std::ostream & stream, const CanonPath & path) { stream << path.abs(); return stream; } std::string CanonPath::makeRelative(const CanonPath & path) const { auto p1 = begin(); auto p2 = path.begin(); for (; p1 != end() && p2 != path.end() && *p1 == *p2; ++p1, ++p2) ; if (p1 == end() && p2 == path.end()) return "."; else if (p1 == end()) return std::string(p2.remaining); else { std::string res; while (p1 != end()) { ++p1; if (!res.empty()) res += '/'; res += ".."; } if (p2 != path.end()) { if (!res.empty()) res += '/'; res += p2.remaining; } return res; } } }
3,397
C++
.cc
124
22.580645
91
0.575823
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,884
users.cc
NixOS_nix/src/libutil/users.cc
#include "util.hh" #include "users.hh" #include "environment-variables.hh" #include "file-system.hh" namespace nix { Path getCacheDir() { auto dir = getEnv("NIX_CACHE_HOME"); if (dir) { return *dir; } else { auto xdgDir = getEnv("XDG_CACHE_HOME"); if (xdgDir) { return *xdgDir + "/nix"; } else { return getHome() + "/.cache/nix"; } } } Path getConfigDir() { auto dir = getEnv("NIX_CONFIG_HOME"); if (dir) { return *dir; } else { auto xdgDir = getEnv("XDG_CONFIG_HOME"); if (xdgDir) { return *xdgDir + "/nix"; } else { return getHome() + "/.config/nix"; } } } std::vector<Path> getConfigDirs() { Path configHome = getConfigDir(); auto configDirs = getEnv("XDG_CONFIG_DIRS").value_or("/etc/xdg"); std::vector<Path> result = tokenizeString<std::vector<std::string>>(configDirs, ":"); for (auto& p : result) { p += "/nix"; } result.insert(result.begin(), configHome); return result; } Path getDataDir() { auto dir = getEnv("NIX_DATA_HOME"); if (dir) { return *dir; } else { auto xdgDir = getEnv("XDG_DATA_HOME"); if (xdgDir) { return *xdgDir + "/nix"; } else { return getHome() + "/.local/share/nix"; } } } Path getStateDir() { auto dir = getEnv("NIX_STATE_HOME"); if (dir) { return *dir; } else { auto xdgDir = getEnv("XDG_STATE_HOME"); if (xdgDir) { return *xdgDir + "/nix"; } else { return getHome() + "/.local/state/nix"; } } } Path createNixStateDir() { Path dir = getStateDir(); createDirs(dir); return dir; } std::string expandTilde(std::string_view path) { // TODO: expand ~user ? auto tilde = path.substr(0, 2); if (tilde == "~/" || tilde == "~") return getHome() + std::string(path.substr(1)); else return std::string(path); } }
2,047
C++
.cc
88
17.579545
89
0.542886
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,885
json-utils.cc
NixOS_nix/src/libutil/json-utils.cc
#include "json-utils.hh" #include "error.hh" #include "types.hh" #include <nlohmann/json_fwd.hpp> #include <iostream> namespace nix { const nlohmann::json * get(const nlohmann::json & map, const std::string & key) { auto i = map.find(key); if (i == map.end()) return nullptr; return &*i; } nlohmann::json * get(nlohmann::json & map, const std::string & key) { auto i = map.find(key); if (i == map.end()) return nullptr; return &*i; } const nlohmann::json & valueAt( const nlohmann::json::object_t & map, const std::string & key) { if (!map.contains(key)) throw Error("Expected JSON object to contain key '%s' but it doesn't: %s", key, nlohmann::json(map).dump()); return map.at(key); } std::optional<nlohmann::json> optionalValueAt(const nlohmann::json::object_t & map, const std::string & key) { if (!map.contains(key)) return std::nullopt; return std::optional { map.at(key) }; } const nlohmann::json * getNullable(const nlohmann::json & value) { return value.is_null() ? nullptr : &value; } /** * Ensure the type of a JSON object is what you expect, failing with a * ensure type if it isn't. * * Use before type conversions and element access to avoid ugly * exceptions, but only part of this module to define the other `get*` * functions. It is too cumbersome and easy to forget to expect regular * JSON code to use it directly. */ static const nlohmann::json & ensureType( const nlohmann::json & value, nlohmann::json::value_type expectedType ) { if (value.type() != expectedType) throw Error( "Expected JSON value to be of type '%s' but it is of type '%s': %s", nlohmann::json(expectedType).type_name(), value.type_name(), value.dump()); return value; } const nlohmann::json::object_t & getObject(const nlohmann::json & value) { return ensureType(value, nlohmann::json::value_t::object).get_ref<const nlohmann::json::object_t &>(); } const nlohmann::json::array_t & getArray(const nlohmann::json & value) { return ensureType(value, nlohmann::json::value_t::array).get_ref<const nlohmann::json::array_t &>(); } const nlohmann::json::string_t & getString(const nlohmann::json & value) { return ensureType(value, nlohmann::json::value_t::string).get_ref<const nlohmann::json::string_t &>(); } const nlohmann::json::number_integer_t & getInteger(const nlohmann::json & value) { return ensureType(value, nlohmann::json::value_t::number_integer).get_ref<const nlohmann::json::number_integer_t &>(); } const nlohmann::json::boolean_t & getBoolean(const nlohmann::json & value) { return ensureType(value, nlohmann::json::value_t::boolean).get_ref<const nlohmann::json::boolean_t &>(); } Strings getStringList(const nlohmann::json & value) { auto & jsonArray = getArray(value); Strings stringList; for (const auto & elem : jsonArray) stringList.push_back(getString(elem)); return stringList; } StringMap getStringMap(const nlohmann::json & value) { auto & jsonObject = getObject(value); StringMap stringMap; for (const auto & [key, value] : jsonObject) stringMap[getString(key)] = getString(value); return stringMap; } StringSet getStringSet(const nlohmann::json & value) { auto & jsonArray = getArray(value); StringSet stringSet; for (const auto & elem : jsonArray) stringSet.insert(getString(elem)); return stringSet; } }
3,481
C++
.cc
102
30.578431
122
0.691137
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,886
memory-source-accessor.cc
NixOS_nix/src/libutil/memory-source-accessor.cc
#include "memory-source-accessor.hh" namespace nix { MemorySourceAccessor::File * MemorySourceAccessor::open(const CanonPath & path, std::optional<File> create) { File * cur = &root; bool newF = false; for (std::string_view name : path) { auto * curDirP = std::get_if<File::Directory>(&cur->raw); if (!curDirP) return nullptr; auto & curDir = *curDirP; auto i = curDir.contents.find(name); if (i == curDir.contents.end()) { if (!create) return nullptr; else { newF = true; i = curDir.contents.insert(i, { std::string { name }, File::Directory {}, }); } } cur = &i->second; } if (newF && create) *cur = std::move(*create); return cur; } std::string MemorySourceAccessor::readFile(const CanonPath & path) { auto * f = open(path, std::nullopt); if (!f) throw Error("file '%s' does not exist", path); if (auto * r = std::get_if<File::Regular>(&f->raw)) return r->contents; else throw Error("file '%s' is not a regular file", path); } bool MemorySourceAccessor::pathExists(const CanonPath & path) { return open(path, std::nullopt); } MemorySourceAccessor::Stat MemorySourceAccessor::File::lstat() const { return std::visit(overloaded { [](const Regular & r) { return Stat { .type = tRegular, .fileSize = r.contents.size(), .isExecutable = r.executable, }; }, [](const Directory &) { return Stat { .type = tDirectory, }; }, [](const Symlink &) { return Stat { .type = tSymlink, }; }, }, this->raw); } std::optional<MemorySourceAccessor::Stat> MemorySourceAccessor::maybeLstat(const CanonPath & path) { const auto * f = open(path, std::nullopt); return f ? std::optional { f->lstat() } : std::nullopt; } MemorySourceAccessor::DirEntries MemorySourceAccessor::readDirectory(const CanonPath & path) { auto * f = open(path, std::nullopt); if (!f) throw Error("file '%s' does not exist", path); if (auto * d = std::get_if<File::Directory>(&f->raw)) { DirEntries res; for (auto & [name, file] : d->contents) res.insert_or_assign(name, file.lstat().type); return res; } else throw Error("file '%s' is not a directory", path); return {}; } std::string MemorySourceAccessor::readLink(const CanonPath & path) { auto * f = open(path, std::nullopt); if (!f) throw Error("file '%s' does not exist", path); if (auto * s = std::get_if<File::Symlink>(&f->raw)) return s->target; else throw Error("file '%s' is not a symbolic link", path); } SourcePath MemorySourceAccessor::addFile(CanonPath path, std::string && contents) { auto * f = open(path, File { File::Regular {} }); if (!f) throw Error("file '%s' cannot be made because some parent file is not a directory", path); if (auto * r = std::get_if<File::Regular>(&f->raw)) r->contents = std::move(contents); else throw Error("file '%s' is not a regular file", path); return SourcePath{ref(shared_from_this()), path}; } using File = MemorySourceAccessor::File; void MemorySink::createDirectory(const CanonPath & path) { auto * f = dst.open(path, File { File::Directory { } }); if (!f) throw Error("file '%s' cannot be made because some parent file is not a directory", path); if (!std::holds_alternative<File::Directory>(f->raw)) throw Error("file '%s' is not a directory", path); }; struct CreateMemoryRegularFile : CreateRegularFileSink { File::Regular & regularFile; CreateMemoryRegularFile(File::Regular & r) : regularFile(r) { } void operator () (std::string_view data) override; void isExecutable() override; void preallocateContents(uint64_t size) override; }; void MemorySink::createRegularFile(const CanonPath & path, std::function<void(CreateRegularFileSink &)> func) { auto * f = dst.open(path, File { File::Regular {} }); if (!f) throw Error("file '%s' cannot be made because some parent file is not a directory", path); if (auto * rp = std::get_if<File::Regular>(&f->raw)) { CreateMemoryRegularFile crf { *rp }; func(crf); } else throw Error("file '%s' is not a regular file", path); } void CreateMemoryRegularFile::isExecutable() { regularFile.executable = true; } void CreateMemoryRegularFile::preallocateContents(uint64_t len) { regularFile.contents.reserve(len); } void CreateMemoryRegularFile::operator () (std::string_view data) { regularFile.contents += data; } void MemorySink::createSymlink(const CanonPath & path, const std::string & target) { auto * f = dst.open(path, File { File::Symlink { } }); if (!f) throw Error("file '%s' cannot be made because some parent file is not a directory", path); if (auto * s = std::get_if<File::Symlink>(&f->raw)) s->target = target; else throw Error("file '%s' is not a symbolic link", path); } ref<SourceAccessor> makeEmptySourceAccessor() { static auto empty = make_ref<MemorySourceAccessor>().cast<SourceAccessor>(); return empty; } }
5,477
C++
.cc
164
27.219512
109
0.611279
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,887
hash.cc
NixOS_nix/src/libutil/hash.cc
#include <iostream> #include <cstring> #include <openssl/crypto.h> #include <openssl/md5.h> #include <openssl/sha.h> #include "args.hh" #include "hash.hh" #include "archive.hh" #include "split.hh" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sodium.h> namespace nix { static size_t regularHashSize(HashAlgorithm type) { switch (type) { case HashAlgorithm::MD5: return md5HashSize; case HashAlgorithm::SHA1: return sha1HashSize; case HashAlgorithm::SHA256: return sha256HashSize; case HashAlgorithm::SHA512: return sha512HashSize; } unreachable(); } const std::set<std::string> hashAlgorithms = {"md5", "sha1", "sha256", "sha512" }; const std::set<std::string> hashFormats = {"base64", "nix32", "base16", "sri" }; Hash::Hash(HashAlgorithm algo) : algo(algo) { hashSize = regularHashSize(algo); assert(hashSize <= maxHashSize); memset(hash, 0, maxHashSize); } bool Hash::operator == (const Hash & h2) const noexcept { if (hashSize != h2.hashSize) return false; for (unsigned int i = 0; i < hashSize; i++) if (hash[i] != h2.hash[i]) return false; return true; } std::strong_ordering Hash::operator <=> (const Hash & h) const noexcept { if (auto cmp = hashSize <=> h.hashSize; cmp != 0) return cmp; for (unsigned int i = 0; i < hashSize; i++) { if (auto cmp = hash[i] <=> h.hash[i]; cmp != 0) return cmp; } if (auto cmp = algo <=> h.algo; cmp != 0) return cmp; return std::strong_ordering::equivalent; } const std::string base16Chars = "0123456789abcdef"; static std::string printHash16(const Hash & hash) { std::string buf; buf.reserve(hash.hashSize * 2); for (unsigned int i = 0; i < hash.hashSize; i++) { buf.push_back(base16Chars[hash.hash[i] >> 4]); buf.push_back(base16Chars[hash.hash[i] & 0x0f]); } return buf; } // omitted: E O U T const std::string nix32Chars = "0123456789abcdfghijklmnpqrsvwxyz"; static std::string printHash32(const Hash & hash) { assert(hash.hashSize); size_t len = hash.base32Len(); assert(len); std::string s; s.reserve(len); for (int n = (int) len - 1; n >= 0; n--) { unsigned int b = n * 5; unsigned int i = b / 8; unsigned int j = b % 8; unsigned char c = (hash.hash[i] >> j) | (i >= hash.hashSize - 1 ? 0 : hash.hash[i + 1] << (8 - j)); s.push_back(nix32Chars[c & 0x1f]); } return s; } std::string printHash16or32(const Hash & hash) { assert(static_cast<char>(hash.algo)); return hash.to_string(hash.algo == HashAlgorithm::MD5 ? HashFormat::Base16 : HashFormat::Nix32, false); } std::string Hash::to_string(HashFormat hashFormat, bool includeAlgo) const { std::string s; if (hashFormat == HashFormat::SRI || includeAlgo) { s += printHashAlgo(algo); s += hashFormat == HashFormat::SRI ? '-' : ':'; } switch (hashFormat) { case HashFormat::Base16: s += printHash16(*this); break; case HashFormat::Nix32: s += printHash32(*this); break; case HashFormat::Base64: case HashFormat::SRI: s += base64Encode(std::string_view((const char *) hash, hashSize)); break; } return s; } Hash Hash::dummy(HashAlgorithm::SHA256); Hash Hash::parseSRI(std::string_view original) { auto rest = original; // Parse the has type before the separater, if there was one. auto hashRaw = splitPrefixTo(rest, '-'); if (!hashRaw) throw BadHash("hash '%s' is not SRI", original); HashAlgorithm parsedType = parseHashAlgo(*hashRaw); return Hash(rest, parsedType, true); } // Mutates the string to eliminate the prefixes when found static std::pair<std::optional<HashAlgorithm>, bool> getParsedTypeAndSRI(std::string_view & rest) { bool isSRI = false; // Parse the hash type before the separator, if there was one. std::optional<HashAlgorithm> optParsedType; { auto hashRaw = splitPrefixTo(rest, ':'); if (!hashRaw) { hashRaw = splitPrefixTo(rest, '-'); if (hashRaw) isSRI = true; } if (hashRaw) optParsedType = parseHashAlgo(*hashRaw); } return {optParsedType, isSRI}; } Hash Hash::parseAnyPrefixed(std::string_view original) { auto rest = original; auto [optParsedType, isSRI] = getParsedTypeAndSRI(rest); // Either the string or user must provide the type, if they both do they // must agree. if (!optParsedType) throw BadHash("hash '%s' does not include a type", rest); return Hash(rest, *optParsedType, isSRI); } Hash Hash::parseAny(std::string_view original, std::optional<HashAlgorithm> optAlgo) { auto rest = original; auto [optParsedType, isSRI] = getParsedTypeAndSRI(rest); // Either the string or user must provide the type, if they both do they // must agree. if (!optParsedType && !optAlgo) throw BadHash("hash '%s' does not include a type, nor is the type otherwise known from context", rest); else if (optParsedType && optAlgo && *optParsedType != *optAlgo) throw BadHash("hash '%s' should have type '%s'", original, printHashAlgo(*optAlgo)); HashAlgorithm hashAlgo = optParsedType ? *optParsedType : *optAlgo; return Hash(rest, hashAlgo, isSRI); } Hash Hash::parseNonSRIUnprefixed(std::string_view s, HashAlgorithm algo) { return Hash(s, algo, false); } Hash::Hash(std::string_view rest, HashAlgorithm algo, bool isSRI) : Hash(algo) { if (!isSRI && rest.size() == base16Len()) { auto parseHexDigit = [&](char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'A' && c <= 'F') return c - 'A' + 10; if (c >= 'a' && c <= 'f') return c - 'a' + 10; throw BadHash("invalid base-16 hash '%s'", rest); }; for (unsigned int i = 0; i < hashSize; i++) { hash[i] = parseHexDigit(rest[i * 2]) << 4 | parseHexDigit(rest[i * 2 + 1]); } } else if (!isSRI && rest.size() == base32Len()) { for (unsigned int n = 0; n < rest.size(); ++n) { char c = rest[rest.size() - n - 1]; unsigned char digit; for (digit = 0; digit < nix32Chars.size(); ++digit) /* !!! slow */ if (nix32Chars[digit] == c) break; if (digit >= 32) throw BadHash("invalid base-32 hash '%s'", rest); unsigned int b = n * 5; unsigned int i = b / 8; unsigned int j = b % 8; hash[i] |= digit << j; if (i < hashSize - 1) { hash[i + 1] |= digit >> (8 - j); } else { if (digit >> (8 - j)) throw BadHash("invalid base-32 hash '%s'", rest); } } } else if (isSRI || rest.size() == base64Len()) { std::string d; try { d = base64Decode(rest); } catch (Error & e) { e.addTrace({}, "While decoding hash '%s'", rest); } if (d.size() != hashSize) throw BadHash("invalid %s hash '%s'", isSRI ? "SRI" : "base-64", rest); assert(hashSize); memcpy(hash, d.data(), hashSize); } else throw BadHash("hash '%s' has wrong length for hash algorithm '%s'", rest, printHashAlgo(this->algo)); } Hash Hash::random(HashAlgorithm algo) { Hash hash(algo); randombytes_buf(hash.hash, hash.hashSize); return hash; } Hash newHashAllowEmpty(std::string_view hashStr, std::optional<HashAlgorithm> ha) { if (hashStr.empty()) { if (!ha) throw BadHash("empty hash requires explicit hash algorithm"); Hash h(*ha); warn("found empty hash, assuming '%s'", h.to_string(HashFormat::SRI, true)); return h; } else return Hash::parseAny(hashStr, ha); } union Ctx { MD5_CTX md5; SHA_CTX sha1; SHA256_CTX sha256; SHA512_CTX sha512; }; static void start(HashAlgorithm ha, Ctx & ctx) { if (ha == HashAlgorithm::MD5) MD5_Init(&ctx.md5); else if (ha == HashAlgorithm::SHA1) SHA1_Init(&ctx.sha1); else if (ha == HashAlgorithm::SHA256) SHA256_Init(&ctx.sha256); else if (ha == HashAlgorithm::SHA512) SHA512_Init(&ctx.sha512); } static void update(HashAlgorithm ha, Ctx & ctx, std::string_view data) { if (ha == HashAlgorithm::MD5) MD5_Update(&ctx.md5, data.data(), data.size()); else if (ha == HashAlgorithm::SHA1) SHA1_Update(&ctx.sha1, data.data(), data.size()); else if (ha == HashAlgorithm::SHA256) SHA256_Update(&ctx.sha256, data.data(), data.size()); else if (ha == HashAlgorithm::SHA512) SHA512_Update(&ctx.sha512, data.data(), data.size()); } static void finish(HashAlgorithm ha, Ctx & ctx, unsigned char * hash) { if (ha == HashAlgorithm::MD5) MD5_Final(hash, &ctx.md5); else if (ha == HashAlgorithm::SHA1) SHA1_Final(hash, &ctx.sha1); else if (ha == HashAlgorithm::SHA256) SHA256_Final(hash, &ctx.sha256); else if (ha == HashAlgorithm::SHA512) SHA512_Final(hash, &ctx.sha512); } Hash hashString(HashAlgorithm ha, std::string_view s) { Ctx ctx; Hash hash(ha); start(ha, ctx); update(ha, ctx, s); finish(ha, ctx, hash.hash); return hash; } Hash hashFile(HashAlgorithm ha, const Path & path) { HashSink sink(ha); readFile(path, sink); return sink.finish().first; } HashSink::HashSink(HashAlgorithm ha) : ha(ha) { ctx = new Ctx; bytes = 0; start(ha, *ctx); } HashSink::~HashSink() { bufPos = 0; delete ctx; } void HashSink::writeUnbuffered(std::string_view data) { bytes += data.size(); update(ha, *ctx, data); } HashResult HashSink::finish() { flush(); Hash hash(ha); nix::finish(ha, *ctx, hash.hash); return HashResult(hash, bytes); } HashResult HashSink::currentHash() { flush(); Ctx ctx2 = *ctx; Hash hash(ha); nix::finish(ha, ctx2, hash.hash); return HashResult(hash, bytes); } Hash compressHash(const Hash & hash, unsigned int newSize) { Hash h(hash.algo); h.hashSize = newSize; for (unsigned int i = 0; i < hash.hashSize; ++i) h.hash[i % newSize] ^= hash.hash[i]; return h; } std::optional<HashFormat> parseHashFormatOpt(std::string_view hashFormatName) { if (hashFormatName == "base16") return HashFormat::Base16; if (hashFormatName == "nix32") return HashFormat::Nix32; if (hashFormatName == "base32") { warn(R"("base32" is a deprecated alias for hash format "nix32".)"); return HashFormat::Nix32; } if (hashFormatName == "base64") return HashFormat::Base64; if (hashFormatName == "sri") return HashFormat::SRI; return std::nullopt; } HashFormat parseHashFormat(std::string_view hashFormatName) { auto opt_f = parseHashFormatOpt(hashFormatName); if (opt_f) return *opt_f; throw UsageError("unknown hash format '%1%', expect 'base16', 'base32', 'base64', or 'sri'", hashFormatName); } std::string_view printHashFormat(HashFormat HashFormat) { switch (HashFormat) { case HashFormat::Base64: return "base64"; case HashFormat::Nix32: return "nix32"; case HashFormat::Base16: return "base16"; case HashFormat::SRI: return "sri"; default: // illegal hash base enum value internally, as opposed to external input // which should be validated with nice error message. assert(false); } } std::optional<HashAlgorithm> parseHashAlgoOpt(std::string_view s) { if (s == "md5") return HashAlgorithm::MD5; if (s == "sha1") return HashAlgorithm::SHA1; if (s == "sha256") return HashAlgorithm::SHA256; if (s == "sha512") return HashAlgorithm::SHA512; return std::nullopt; } HashAlgorithm parseHashAlgo(std::string_view s) { auto opt_h = parseHashAlgoOpt(s); if (opt_h) return *opt_h; else throw UsageError("unknown hash algorithm '%1%', expect 'md5', 'sha1', 'sha256', or 'sha512'", s); } std::string_view printHashAlgo(HashAlgorithm ha) { switch (ha) { case HashAlgorithm::MD5: return "md5"; case HashAlgorithm::SHA1: return "sha1"; case HashAlgorithm::SHA256: return "sha256"; case HashAlgorithm::SHA512: return "sha512"; default: // illegal hash type enum value internally, as opposed to external input // which should be validated with nice error message. assert(false); } } }
12,570
C++
.cc
376
28.034574
113
0.625826
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
10,888
compression.cc
NixOS_nix/src/libutil/compression.cc
#include "compression.hh" #include "signals.hh" #include "tarfile.hh" #include "finally.hh" #include "logging.hh" #include <archive.h> #include <archive_entry.h> #include <cstdio> #include <cstring> #include <brotli/decode.h> #include <brotli/encode.h> namespace nix { static const int COMPRESSION_LEVEL_DEFAULT = -1; // Don't feed brotli too much at once. struct ChunkedCompressionSink : CompressionSink { uint8_t outbuf[32 * 1024]; void writeUnbuffered(std::string_view data) override { const size_t CHUNK_SIZE = sizeof(outbuf) << 2; while (!data.empty()) { size_t n = std::min(CHUNK_SIZE, data.size()); writeInternal(data.substr(0, n)); data.remove_prefix(n); } } virtual void writeInternal(std::string_view data) = 0; }; struct ArchiveDecompressionSource : Source { std::unique_ptr<TarArchive> archive = 0; Source & src; std::optional<std::string> compressionMethod; ArchiveDecompressionSource(Source & src, std::optional<std::string> compressionMethod = std::nullopt) : src(src) , compressionMethod(std::move(compressionMethod)) { } ~ArchiveDecompressionSource() override {} size_t read(char * data, size_t len) override { struct archive_entry * ae; if (!archive) { archive = std::make_unique<TarArchive>(src, /*raw*/ true, compressionMethod); this->archive->check(archive_read_next_header(this->archive->archive, &ae), "failed to read header (%s)"); if (archive_filter_count(this->archive->archive) < 2) { throw CompressionError("input compression not recognized"); } } ssize_t result = archive_read_data(this->archive->archive, data, len); if (result > 0) return result; if (result == 0) { throw EndOfFile("reached end of compressed file"); } this->archive->check(result, "failed to read compressed data (%s)"); return result; } }; struct ArchiveCompressionSink : CompressionSink { Sink & nextSink; struct archive * archive; ArchiveCompressionSink(Sink & nextSink, std::string format, bool parallel, int level = COMPRESSION_LEVEL_DEFAULT) : nextSink(nextSink) { archive = archive_write_new(); if (!archive) throw Error("failed to initialize libarchive"); check(archive_write_add_filter_by_name(archive, format.c_str()), "couldn't initialize compression (%s)"); check(archive_write_set_format_raw(archive)); if (parallel) check(archive_write_set_filter_option(archive, format.c_str(), "threads", "0")); if (level != COMPRESSION_LEVEL_DEFAULT) check(archive_write_set_filter_option( archive, format.c_str(), "compression-level", std::to_string(level).c_str())); // disable internal buffering check(archive_write_set_bytes_per_block(archive, 0)); // disable output padding check(archive_write_set_bytes_in_last_block(archive, 1)); open(); } ~ArchiveCompressionSink() override { if (archive) archive_write_free(archive); } void finish() override { flush(); check(archive_write_close(archive)); } void check(int err, const std::string & reason = "failed to compress (%s)") { if (err == ARCHIVE_EOF) throw EndOfFile("reached end of archive"); else if (err != ARCHIVE_OK) throw Error(reason, archive_error_string(this->archive)); } void writeUnbuffered(std::string_view data) override { ssize_t result = archive_write_data(archive, data.data(), data.length()); if (result <= 0) check(result); } private: void open() { check(archive_write_open(archive, this, nullptr, ArchiveCompressionSink::callback_write, nullptr)); auto ae = archive_entry_new(); archive_entry_set_filetype(ae, AE_IFREG); check(archive_write_header(archive, ae)); archive_entry_free(ae); } static ssize_t callback_write(struct archive * archive, void * _self, const void * buffer, size_t length) { auto self = (ArchiveCompressionSink *) _self; self->nextSink({(const char *) buffer, length}); return length; } }; struct NoneSink : CompressionSink { Sink & nextSink; NoneSink(Sink & nextSink, int level = COMPRESSION_LEVEL_DEFAULT) : nextSink(nextSink) { if (level != COMPRESSION_LEVEL_DEFAULT) warn("requested compression level '%d' not supported by compression method 'none'", level); } void finish() override { flush(); } void writeUnbuffered(std::string_view data) override { nextSink(data); } }; struct BrotliDecompressionSink : ChunkedCompressionSink { Sink & nextSink; BrotliDecoderState * state; bool finished = false; BrotliDecompressionSink(Sink & nextSink) : nextSink(nextSink) { state = BrotliDecoderCreateInstance(nullptr, nullptr, nullptr); if (!state) throw CompressionError("unable to initialize brotli decoder"); } ~BrotliDecompressionSink() { BrotliDecoderDestroyInstance(state); } void finish() override { flush(); writeInternal({}); } void writeInternal(std::string_view data) override { auto next_in = (const uint8_t *) data.data(); size_t avail_in = data.size(); uint8_t * next_out = outbuf; size_t avail_out = sizeof(outbuf); while (!finished && (!data.data() || avail_in)) { checkInterrupt(); if (!BrotliDecoderDecompressStream(state, &avail_in, &next_in, &avail_out, &next_out, nullptr)) throw CompressionError("error while decompressing brotli file"); if (avail_out < sizeof(outbuf) || avail_in == 0) { nextSink({(char *) outbuf, sizeof(outbuf) - avail_out}); next_out = outbuf; avail_out = sizeof(outbuf); } finished = BrotliDecoderIsFinished(state); } } }; std::string decompress(const std::string & method, std::string_view in) { StringSink ssink; auto sink = makeDecompressionSink(method, ssink); (*sink)(in); sink->finish(); return std::move(ssink.s); } std::unique_ptr<FinishSink> makeDecompressionSink(const std::string & method, Sink & nextSink) { if (method == "none" || method == "") return std::make_unique<NoneSink>(nextSink); else if (method == "br") return std::make_unique<BrotliDecompressionSink>(nextSink); else return sourceToSink([method, &nextSink](Source & source) { auto decompressionSource = std::make_unique<ArchiveDecompressionSource>(source, method); decompressionSource->drainInto(nextSink); }); } struct BrotliCompressionSink : ChunkedCompressionSink { Sink & nextSink; uint8_t outbuf[BUFSIZ]; BrotliEncoderState * state; bool finished = false; BrotliCompressionSink(Sink & nextSink) : nextSink(nextSink) { state = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr); if (!state) throw CompressionError("unable to initialise brotli encoder"); } ~BrotliCompressionSink() { BrotliEncoderDestroyInstance(state); } void finish() override { flush(); writeInternal({}); } void writeInternal(std::string_view data) override { auto next_in = (const uint8_t *) data.data(); size_t avail_in = data.size(); uint8_t * next_out = outbuf; size_t avail_out = sizeof(outbuf); while (!finished && (!data.data() || avail_in)) { checkInterrupt(); if (!BrotliEncoderCompressStream( state, data.data() ? BROTLI_OPERATION_PROCESS : BROTLI_OPERATION_FINISH, &avail_in, &next_in, &avail_out, &next_out, nullptr)) throw CompressionError("error while compressing brotli compression"); if (avail_out < sizeof(outbuf) || avail_in == 0) { nextSink({(const char *) outbuf, sizeof(outbuf) - avail_out}); next_out = outbuf; avail_out = sizeof(outbuf); } finished = BrotliEncoderIsFinished(state); } } }; ref<CompressionSink> makeCompressionSink(const std::string & method, Sink & nextSink, const bool parallel, int level) { std::vector<std::string> la_supports = { "bzip2", "compress", "grzip", "gzip", "lrzip", "lz4", "lzip", "lzma", "lzop", "xz", "zstd"}; if (std::find(la_supports.begin(), la_supports.end(), method) != la_supports.end()) { return make_ref<ArchiveCompressionSink>(nextSink, method, parallel, level); } if (method == "none") return make_ref<NoneSink>(nextSink); else if (method == "br") return make_ref<BrotliCompressionSink>(nextSink); else throw UnknownCompressionMethod("unknown compression method '%s'", method); } std::string compress(const std::string & method, std::string_view in, const bool parallel, int level) { StringSink ssink; auto sink = makeCompressionSink(method, ssink, parallel, level); (*sink)(in); sink->finish(); return std::move(ssink.s); } }
9,606
C++
.cc
270
28.177778
118
0.621343
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
10,889
strings.cc
NixOS_nix/src/libutil/strings.cc
#include <filesystem> #include <string> #include <sstream> #include "strings-inline.hh" #include "os-string.hh" namespace nix { struct view_stringbuf : public std::stringbuf { inline std::string_view toView() { auto begin = pbase(); return {begin, begin + pubseekoff(0, std::ios_base::cur, std::ios_base::out)}; } }; std::string_view toView(const std::ostringstream & os) { auto buf = static_cast<view_stringbuf *>(os.rdbuf()); return buf->toView(); } template std::list<std::string> tokenizeString(std::string_view s, std::string_view separators); template std::set<std::string> tokenizeString(std::string_view s, std::string_view separators); template std::vector<std::string> tokenizeString(std::string_view s, std::string_view separators); template std::list<std::string> splitString(std::string_view s, std::string_view separators); template std::set<std::string> splitString(std::string_view s, std::string_view separators); template std::vector<std::string> splitString(std::string_view s, std::string_view separators); template std::list<OsString> basicSplitString(std::basic_string_view<OsChar> s, std::basic_string_view<OsChar> separators); template std::string concatStringsSep(std::string_view, const std::list<std::string> &); template std::string concatStringsSep(std::string_view, const std::set<std::string> &); template std::string concatStringsSep(std::string_view, const std::vector<std::string> &); typedef std::string_view strings_2[2]; template std::string concatStringsSep(std::string_view, const strings_2 &); typedef std::string_view strings_3[3]; template std::string concatStringsSep(std::string_view, const strings_3 &); typedef std::string_view strings_4[4]; template std::string concatStringsSep(std::string_view, const strings_4 &); template std::string dropEmptyInitThenConcatStringsSep(std::string_view, const std::list<std::string> &); template std::string dropEmptyInitThenConcatStringsSep(std::string_view, const std::set<std::string> &); template std::string dropEmptyInitThenConcatStringsSep(std::string_view, const std::vector<std::string> &); } // namespace nix
2,149
C++
.cc
40
51.55
107
0.757865
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,890
serialise.cc
NixOS_nix/src/libutil/serialise.cc
#include "serialise.hh" #include "signals.hh" #include "util.hh" #include <cstring> #include <cerrno> #include <memory> #include <boost/coroutine2/coroutine.hpp> #ifdef _WIN32 # include <fileapi.h> # include <winsock2.h> # include "windows-error.hh" #else # include <poll.h> #endif namespace nix { void BufferedSink::operator () (std::string_view data) { if (!buffer) buffer = decltype(buffer)(new char[bufSize]); while (!data.empty()) { /* Optimisation: bypass the buffer if the data exceeds the buffer size. */ if (bufPos + data.size() >= bufSize) { flush(); writeUnbuffered(data); break; } /* Otherwise, copy the bytes to the buffer. Flush the buffer when it's full. */ size_t n = bufPos + data.size() > bufSize ? bufSize - bufPos : data.size(); memcpy(buffer.get() + bufPos, data.data(), n); data.remove_prefix(n); bufPos += n; if (bufPos == bufSize) flush(); } } void BufferedSink::flush() { if (bufPos == 0) return; size_t n = bufPos; bufPos = 0; // don't trigger the assert() in ~BufferedSink() writeUnbuffered({buffer.get(), n}); } FdSink::~FdSink() { try { flush(); } catch (...) { ignoreExceptionInDestructor(); } } void FdSink::writeUnbuffered(std::string_view data) { written += data.size(); try { writeFull(fd, data); } catch (SystemError & e) { _good = false; throw; } } bool FdSink::good() { return _good; } void Source::operator () (char * data, size_t len) { while (len) { size_t n = read(data, len); data += n; len -= n; } } void Source::operator () (std::string_view data) { (*this)((char *)data.data(), data.size()); } void Source::drainInto(Sink & sink) { std::string s; std::array<char, 8192> buf; while (true) { size_t n; try { n = read(buf.data(), buf.size()); sink({buf.data(), n}); } catch (EndOfFile &) { break; } } } std::string Source::drain() { StringSink s; drainInto(s); return std::move(s.s); } size_t BufferedSource::read(char * data, size_t len) { if (!buffer) buffer = decltype(buffer)(new char[bufSize]); if (!bufPosIn) bufPosIn = readUnbuffered(buffer.get(), bufSize); /* Copy out the data in the buffer. */ size_t n = len > bufPosIn - bufPosOut ? bufPosIn - bufPosOut : len; memcpy(data, buffer.get() + bufPosOut, n); bufPosOut += n; if (bufPosIn == bufPosOut) bufPosIn = bufPosOut = 0; return n; } bool BufferedSource::hasData() { return bufPosOut < bufPosIn; } size_t FdSource::readUnbuffered(char * data, size_t len) { #ifdef _WIN32 DWORD n; checkInterrupt(); if (!::ReadFile(fd, data, len, &n, NULL)) { _good = false; throw windows::WinError("ReadFile when FdSource::readUnbuffered"); } #else ssize_t n; do { checkInterrupt(); n = ::read(fd, data, len); } while (n == -1 && errno == EINTR); if (n == -1) { _good = false; throw SysError("reading from file"); } if (n == 0) { _good = false; throw EndOfFile(std::string(*endOfFileError)); } #endif read += n; return n; } bool FdSource::good() { return _good; } bool FdSource::hasData() { if (BufferedSource::hasData()) return true; while (true) { fd_set fds; FD_ZERO(&fds); int fd_ = fromDescriptorReadOnly(fd); FD_SET(fd_, &fds); struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 0; auto n = select(fd_ + 1, &fds, nullptr, nullptr, &timeout); if (n < 0) { if (errno == EINTR) continue; throw SysError("polling file descriptor"); } return FD_ISSET(fd, &fds); } } size_t StringSource::read(char * data, size_t len) { if (pos == s.size()) throw EndOfFile("end of string reached"); size_t n = s.copy(data, len, pos); pos += n; return n; } #if BOOST_VERSION >= 106300 && BOOST_VERSION < 106600 #error Coroutines are broken in this version of Boost! #endif std::unique_ptr<FinishSink> sourceToSink(std::function<void(Source &)> fun) { struct SourceToSink : FinishSink { typedef boost::coroutines2::coroutine<bool> coro_t; std::function<void(Source &)> fun; std::optional<coro_t::push_type> coro; SourceToSink(std::function<void(Source &)> fun) : fun(fun) { } std::string_view cur; void operator () (std::string_view in) override { if (in.empty()) return; cur = in; if (!coro) { coro = coro_t::push_type([&](coro_t::pull_type & yield) { LambdaSource source([&](char * out, size_t out_len) { if (cur.empty()) { yield(); if (yield.get()) throw EndOfFile("coroutine has finished"); } size_t n = std::min(cur.size(), out_len); memcpy(out, cur.data(), n); cur.remove_prefix(n); return n; }); fun(source); }); } if (!*coro) { unreachable(); } if (!cur.empty()) { (*coro)(false); } } void finish() override { if (coro && *coro) (*coro)(true); } }; return std::make_unique<SourceToSink>(fun); } std::unique_ptr<Source> sinkToSource( std::function<void(Sink &)> fun, std::function<void()> eof) { struct SinkToSource : Source { typedef boost::coroutines2::coroutine<std::string> coro_t; std::function<void(Sink &)> fun; std::function<void()> eof; std::optional<coro_t::pull_type> coro; SinkToSource(std::function<void(Sink &)> fun, std::function<void()> eof) : fun(fun), eof(eof) { } std::string cur; size_t pos = 0; size_t read(char * data, size_t len) override { if (!coro) { coro = coro_t::pull_type([&](coro_t::push_type & yield) { LambdaSink sink([&](std::string_view data) { if (!data.empty()) yield(std::string(data)); }); fun(sink); }); } if (!*coro) { eof(); unreachable(); } if (pos == cur.size()) { if (!cur.empty()) { (*coro)(); } cur = coro->get(); pos = 0; } auto n = std::min(cur.size() - pos, len); memcpy(data, cur.data() + pos, n); pos += n; return n; } }; return std::make_unique<SinkToSource>(fun, eof); } void writePadding(size_t len, Sink & sink) { if (len % 8) { char zero[8]; memset(zero, 0, sizeof(zero)); sink({zero, 8 - (len % 8)}); } } void writeString(std::string_view data, Sink & sink) { sink << data.size(); sink(data); writePadding(data.size(), sink); } Sink & operator << (Sink & sink, std::string_view s) { writeString(s, sink); return sink; } template<class T> void writeStrings(const T & ss, Sink & sink) { sink << ss.size(); for (auto & i : ss) sink << i; } Sink & operator << (Sink & sink, const Strings & s) { writeStrings(s, sink); return sink; } Sink & operator << (Sink & sink, const StringSet & s) { writeStrings(s, sink); return sink; } Sink & operator << (Sink & sink, const Error & ex) { auto & info = ex.info(); sink << "Error" << info.level << "Error" // removed << info.msg.str() << 0 // FIXME: info.errPos << info.traces.size(); for (auto & trace : info.traces) { sink << 0; // FIXME: trace.pos sink << trace.hint.str(); } return sink; } void readPadding(size_t len, Source & source) { if (len % 8) { char zero[8]; size_t n = 8 - (len % 8); source(zero, n); for (unsigned int i = 0; i < n; i++) if (zero[i]) throw SerialisationError("non-zero padding"); } } size_t readString(char * buf, size_t max, Source & source) { auto len = readNum<size_t>(source); if (len > max) throw SerialisationError("string is too long"); source(buf, len); readPadding(len, source); return len; } std::string readString(Source & source, size_t max) { auto len = readNum<size_t>(source); if (len > max) throw SerialisationError("string is too long"); std::string res(len, 0); source(res.data(), len); readPadding(len, source); return res; } Source & operator >> (Source & in, std::string & s) { s = readString(in); return in; } template<class T> T readStrings(Source & source) { auto count = readNum<size_t>(source); T ss; while (count--) ss.insert(ss.end(), readString(source)); return ss; } template Paths readStrings(Source & source); template PathSet readStrings(Source & source); Error readError(Source & source) { auto type = readString(source); assert(type == "Error"); auto level = (Verbosity) readInt(source); auto name = readString(source); // removed auto msg = readString(source); ErrorInfo info { .level = level, .msg = HintFmt(msg), }; auto havePos = readNum<size_t>(source); assert(havePos == 0); auto nrTraces = readNum<size_t>(source); for (size_t i = 0; i < nrTraces; ++i) { havePos = readNum<size_t>(source); assert(havePos == 0); info.traces.push_back(Trace { .hint = HintFmt(readString(source)) }); } return Error(std::move(info)); } void StringSink::operator () (std::string_view data) { s.append(data); } size_t ChainSource::read(char * data, size_t len) { if (useSecond) { return source2.read(data, len); } else { try { return source1.read(data, len); } catch (EndOfFile &) { useSecond = true; return this->read(data, len); } } } }
10,444
C++
.cc
379
20.825858
83
0.546266
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
10,891
suggestions.cc
NixOS_nix/src/libutil/suggestions.cc
#include "suggestions.hh" #include "ansicolor.hh" #include "terminal.hh" #include <algorithm> #include <sstream> namespace nix { int levenshteinDistance(std::string_view first, std::string_view second) { // Implementation borrowed from // https://en.wikipedia.org/wiki/Levenshtein_distance#Iterative_with_two_matrix_rows int m = first.size(); int n = second.size(); auto v0 = std::vector<int>(n+1); auto v1 = std::vector<int>(n+1); for (auto i = 0; i <= n; i++) v0[i] = i; for (auto i = 0; i < m; i++) { v1[0] = i+1; for (auto j = 0; j < n; j++) { auto deletionCost = v0[j+1] + 1; auto insertionCost = v1[j] + 1; auto substitutionCost = first[i] == second[j] ? v0[j] : v0[j] + 1; v1[j+1] = std::min({deletionCost, insertionCost, substitutionCost}); } std::swap(v0, v1); } return v0[n]; } Suggestions Suggestions::bestMatches ( const std::set<std::string> & allMatches, std::string_view query) { std::set<Suggestion> res; for (const auto & possibleMatch : allMatches) { res.insert(Suggestion { .distance = levenshteinDistance(query, possibleMatch), .suggestion = possibleMatch, }); } return Suggestions { res }; } Suggestions Suggestions::trim(int limit, int maxDistance) const { std::set<Suggestion> res; int count = 0; for (auto & elt : suggestions) { if (count >= limit || elt.distance > maxDistance) break; count++; res.insert(elt); } return Suggestions{res}; } std::string Suggestion::to_string() const { return ANSI_WARNING + filterANSIEscapes(suggestion) + ANSI_NORMAL; } std::string Suggestions::to_string() const { switch (suggestions.size()) { case 0: return ""; case 1: return suggestions.begin()->to_string(); default: { std::string res = "one of "; auto iter = suggestions.begin(); res += iter->to_string(); // Iter can’t be end() because the container isn’t null iter++; auto last = suggestions.end(); last--; for ( ; iter != suggestions.end() ; iter++) { res += (iter == last) ? " or " : ", "; res += iter->to_string(); } return res; } } } Suggestions & Suggestions::operator+=(const Suggestions & other) { suggestions.insert( other.suggestions.begin(), other.suggestions.end() ); return *this; } std::ostream & operator<<(std::ostream & str, const Suggestion & suggestion) { return str << suggestion.to_string(); } std::ostream & operator<<(std::ostream & str, const Suggestions & suggestions) { return str << suggestions.to_string(); } }
2,867
C++
.cc
95
23.778947
93
0.583546
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
10,892
args.cc
NixOS_nix/src/libutil/args.cc
#include "args.hh" #include "args/root.hh" #include "hash.hh" #include "environment-variables.hh" #include "signals.hh" #include "users.hh" #include "json-utils.hh" #include <fstream> #include <string> #include <regex> #ifndef _WIN32 # include <glob.h> #endif namespace nix { void Args::addFlag(Flag && flag_) { auto flag = std::make_shared<Flag>(std::move(flag_)); if (flag->handler.arity != ArityAny) assert(flag->handler.arity == flag->labels.size()); assert(flag->longName != ""); longFlags[flag->longName] = flag; for (auto & alias : flag->aliases) longFlags[alias] = flag; if (flag->shortName) shortFlags[flag->shortName] = flag; } void Args::removeFlag(const std::string & longName) { auto flag = longFlags.find(longName); assert(flag != longFlags.end()); if (flag->second->shortName) shortFlags.erase(flag->second->shortName); longFlags.erase(flag); } void Completions::setType(AddCompletions::Type t) { type = t; } void Completions::add(std::string completion, std::string description) { description = trim(description); // ellipsize overflowing content on the back of the description auto end_index = description.find_first_of(".\n"); if (end_index != std::string::npos) { auto needs_ellipsis = end_index != description.size() - 1; description.resize(end_index); if (needs_ellipsis) description.append(" [...]"); } completions.insert(Completion { .completion = completion, .description = description }); } auto Completion::operator<=>(const Completion & other) const noexcept = default; std::string completionMarker = "___COMPLETE___"; RootArgs & Args::getRoot() { Args * p = this; while (p->parent) p = p->parent; auto * res = dynamic_cast<RootArgs *>(p); assert(res); return *res; } std::optional<std::string> RootArgs::needsCompletion(std::string_view s) { if (!completions) return {}; auto i = s.find(completionMarker); if (i != std::string::npos) return std::string(s.begin(), i); return {}; } /** * Basically this is `typedef std::optional<Parser> Parser(std::string_view s, Strings & r);` * * Except we can't recursively reference the Parser typedef, so we have to write a class. */ struct Parser { std::string_view remaining; /** * @brief Parse the next character(s) */ virtual void operator()(std::shared_ptr<Parser> & state, Strings & r) = 0; Parser(std::string_view s) : remaining(s) {}; virtual ~Parser() { }; }; struct ParseQuoted : public Parser { /** * @brief Accumulated string * * Parsed argument up to this point. */ std::string acc; ParseQuoted(std::string_view s) : Parser(s) {}; virtual void operator()(std::shared_ptr<Parser> & state, Strings & r) override; }; struct ParseUnquoted : public Parser { /** * @brief Accumulated string * * Parsed argument up to this point. Empty string is not representable in * unquoted syntax, so we use it for the initial state. */ std::string acc; ParseUnquoted(std::string_view s) : Parser(s) {}; virtual void operator()(std::shared_ptr<Parser> & state, Strings & r) override { if (remaining.empty()) { if (!acc.empty()) r.push_back(acc); state = nullptr; // done return; } switch (remaining[0]) { case ' ': case '\t': case '\n': case '\r': if (!acc.empty()) r.push_back(acc); state = std::make_shared<ParseUnquoted>(ParseUnquoted(remaining.substr(1))); return; case '`': if (remaining.size() > 1 && remaining[1] == '`') { state = std::make_shared<ParseQuoted>(ParseQuoted(remaining.substr(2))); return; } else throw Error("single backtick is not a supported syntax in the nix shebang."); // reserved characters // meaning to be determined, or may be reserved indefinitely so that // #!nix syntax looks unambiguous case '$': case '*': case '~': case '<': case '>': case '|': case ';': case '(': case ')': case '[': case ']': case '{': case '}': case '\'': case '"': case '\\': throw Error("unsupported unquoted character in nix shebang: " + std::string(1, remaining[0]) + ". Use double backticks to escape?"); case '#': if (acc.empty()) { throw Error ("unquoted nix shebang argument cannot start with #. Use double backticks to escape?"); } else { acc += remaining[0]; remaining = remaining.substr(1); return; } default: acc += remaining[0]; remaining = remaining.substr(1); return; } assert(false); } }; void ParseQuoted::operator()(std::shared_ptr<Parser> &state, Strings & r) { if (remaining.empty()) { throw Error("unterminated quoted string in nix shebang"); } switch (remaining[0]) { case ' ': if ((remaining.size() == 3 && remaining[1] == '`' && remaining[2] == '`') || (remaining.size() > 3 && remaining[1] == '`' && remaining[2] == '`' && remaining[3] != '`')) { // exactly two backticks mark the end of a quoted string, but a preceding space is ignored if present. state = std::make_shared<ParseUnquoted>(ParseUnquoted(remaining.substr(3))); r.push_back(acc); return; } else { // just a normal space acc += remaining[0]; remaining = remaining.substr(1); return; } case '`': // exactly two backticks mark the end of a quoted string if ((remaining.size() == 2 && remaining[1] == '`') || (remaining.size() > 2 && remaining[1] == '`' && remaining[2] != '`')) { state = std::make_shared<ParseUnquoted>(ParseUnquoted(remaining.substr(2))); r.push_back(acc); return; } // a sequence of at least 3 backticks is one escape-backtick which is ignored, followed by any number of backticks, which are verbatim else if (remaining.size() >= 3 && remaining[1] == '`' && remaining[2] == '`') { // ignore "escape" backtick remaining = remaining.substr(1); // add the rest while (remaining.size() > 0 && remaining[0] == '`') { acc += '`'; remaining = remaining.substr(1); } return; } else { acc += remaining[0]; remaining = remaining.substr(1); return; } default: acc += remaining[0]; remaining = remaining.substr(1); return; } assert(false); } Strings parseShebangContent(std::string_view s) { Strings result; std::shared_ptr<Parser> parserState(std::make_shared<ParseUnquoted>(ParseUnquoted(s))); // trampoline == iterated strategy pattern while (parserState) { auto currentState = parserState; (*currentState)(parserState, result); } return result; } void RootArgs::parseCmdline(const Strings & _cmdline, bool allowShebang) { Strings pendingArgs; bool dashDash = false; Strings cmdline(_cmdline); if (auto s = getEnv("NIX_GET_COMPLETIONS")) { size_t n = std::stoi(*s); assert(n > 0 && n <= cmdline.size()); *std::next(cmdline.begin(), n - 1) += completionMarker; completions = std::make_shared<Completions>(); verbosity = lvlError; } // Heuristic to see if we're invoked as a shebang script, namely, // if we have at least one argument, it's the name of an // executable file, and it starts with "#!". Strings savedArgs; if (allowShebang){ auto script = *cmdline.begin(); try { std::ifstream stream(script); char shebang[3]={0,0,0}; stream.get(shebang,3); if (strncmp(shebang,"#!",2) == 0){ for (auto pos = std::next(cmdline.begin()); pos != cmdline.end();pos++) savedArgs.push_back(*pos); cmdline.clear(); std::string line; std::getline(stream,line); static const std::string commentChars("#/\\%@*-("); std::string shebangContent; while (std::getline(stream,line) && !line.empty() && commentChars.find(line[0]) != std::string::npos){ line = chomp(line); std::smatch match; // We match one space after `nix` so that we preserve indentation. // No space is necessary for an empty line. An empty line has basically no effect. if (std::regex_match(line, match, std::regex("^#!\\s*nix(:? |$)(.*)$"))) shebangContent += std::string_view{match[2].first, match[2].second} + "\n"; } for (const auto & word : parseShebangContent(shebangContent)) { cmdline.push_back(word); } cmdline.push_back(script); commandBaseDir = dirOf(script); for (auto pos = savedArgs.begin(); pos != savedArgs.end();pos++) cmdline.push_back(*pos); } } catch (SystemError &) { } } for (auto pos = cmdline.begin(); pos != cmdline.end(); ) { auto arg = *pos; /* Expand compound dash options (i.e., `-qlf' -> `-q -l -f', `-j3` -> `-j 3`). */ if (!dashDash && arg.length() > 2 && arg[0] == '-' && arg[1] != '-' && isalpha(arg[1])) { *pos = (std::string) "-" + arg[1]; auto next = pos; ++next; for (unsigned int j = 2; j < arg.length(); j++) if (isalpha(arg[j])) cmdline.insert(next, (std::string) "-" + arg[j]); else { cmdline.insert(next, std::string(arg, j)); break; } arg = *pos; } if (!dashDash && arg == "--") { dashDash = true; ++pos; } else if (!dashDash && std::string(arg, 0, 1) == "-") { if (!processFlag(pos, cmdline.end())) throw UsageError("unrecognised flag '%1%'", arg); } else { pos = rewriteArgs(cmdline, pos); pendingArgs.push_back(*pos++); if (processArgs(pendingArgs, false)) pendingArgs.clear(); } } processArgs(pendingArgs, true); initialFlagsProcessed(); /* Now that we are done parsing, make sure that any experimental * feature required by the flags is enabled */ for (auto & f : flagExperimentalFeatures) experimentalFeatureSettings.require(f); /* Now that all the other args are processed, run the deferred completions. */ for (auto d : deferredCompletions) d.completer(*completions, d.n, d.prefix); } Path Args::getCommandBaseDir() const { assert(parent); return parent->getCommandBaseDir(); } Path RootArgs::getCommandBaseDir() const { return commandBaseDir; } bool Args::processFlag(Strings::iterator & pos, Strings::iterator end) { assert(pos != end); auto & rootArgs = getRoot(); auto process = [&](const std::string & name, const Flag & flag) -> bool { ++pos; if (auto & f = flag.experimentalFeature) rootArgs.flagExperimentalFeatures.insert(*f); std::vector<std::string> args; bool anyCompleted = false; for (size_t n = 0 ; n < flag.handler.arity; ++n) { if (pos == end) { if (flag.handler.arity == ArityAny || anyCompleted) break; throw UsageError( "flag '%s' requires %d argument(s), but only %d were given", name, flag.handler.arity, n); } if (auto prefix = rootArgs.needsCompletion(*pos)) { anyCompleted = true; if (flag.completer) { rootArgs.deferredCompletions.push_back({ .completer = flag.completer, .n = n, .prefix = *prefix, }); } } args.push_back(*pos++); } if (!anyCompleted) flag.handler.fun(std::move(args)); return true; }; if (std::string(*pos, 0, 2) == "--") { if (auto prefix = rootArgs.needsCompletion(*pos)) { for (auto & [name, flag] : longFlags) { if (!hiddenCategories.count(flag->category) && hasPrefix(name, std::string(*prefix, 2))) { if (auto & f = flag->experimentalFeature) rootArgs.flagExperimentalFeatures.insert(*f); rootArgs.completions->add("--" + name, flag->description); } } return false; } auto i = longFlags.find(std::string(*pos, 2)); if (i == longFlags.end()) return false; return process("--" + i->first, *i->second); } if (std::string(*pos, 0, 1) == "-" && pos->size() == 2) { auto c = (*pos)[1]; auto i = shortFlags.find(c); if (i == shortFlags.end()) return false; return process(std::string("-") + c, *i->second); } if (auto prefix = rootArgs.needsCompletion(*pos)) { if (prefix == "-") { rootArgs.completions->add("--"); for (auto & [flagName, flag] : shortFlags) if (experimentalFeatureSettings.isEnabled(flag->experimentalFeature)) rootArgs.completions->add(std::string("-") + flagName, flag->description); } } return false; } bool Args::processArgs(const Strings & args, bool finish) { if (expectedArgs.empty()) { if (!args.empty()) throw UsageError("unexpected argument '%1%'", args.front()); return true; } auto & rootArgs = getRoot(); auto & exp = expectedArgs.front(); bool res = false; if ((exp.handler.arity == ArityAny && finish) || (exp.handler.arity != ArityAny && args.size() == exp.handler.arity)) { std::vector<std::string> ss; bool anyCompleted = false; for (const auto &[n, s] : enumerate(args)) { if (auto prefix = rootArgs.needsCompletion(s)) { anyCompleted = true; ss.push_back(*prefix); if (exp.completer) { rootArgs.deferredCompletions.push_back({ .completer = exp.completer, .n = n, .prefix = *prefix, }); } } else ss.push_back(s); } if (!anyCompleted) exp.handler.fun(ss); /* Move the list element to the processedArgs. This is almost the same as `processedArgs.push_back(expectedArgs.front()); expectedArgs.pop_front()`, except that it will only adjust the next and prev pointers of the list elements, meaning the actual contents don't move in memory. This is critical to prevent invalidating internal pointers! */ processedArgs.splice( processedArgs.end(), expectedArgs, expectedArgs.begin(), ++expectedArgs.begin()); res = true; } if (finish && !expectedArgs.empty() && !expectedArgs.front().optional) throw UsageError("more arguments are required"); return res; } nlohmann::json Args::toJSON() { auto flags = nlohmann::json::object(); for (auto & [name, flag] : longFlags) { auto j = nlohmann::json::object(); j["hiddenCategory"] = hiddenCategories.count(flag->category) > 0; if (flag->aliases.count(name)) continue; if (flag->shortName) j["shortName"] = std::string(1, flag->shortName); if (flag->description != "") j["description"] = trim(flag->description); j["category"] = flag->category; if (flag->handler.arity != ArityAny) j["arity"] = flag->handler.arity; if (!flag->labels.empty()) j["labels"] = flag->labels; j["experimental-feature"] = flag->experimentalFeature; flags[name] = std::move(j); } auto args = nlohmann::json::array(); for (auto & arg : expectedArgs) { auto j = nlohmann::json::object(); j["label"] = arg.label; j["optional"] = arg.optional; if (arg.handler.arity != ArityAny) j["arity"] = arg.handler.arity; args.push_back(std::move(j)); } auto res = nlohmann::json::object(); res["description"] = trim(description()); res["flags"] = std::move(flags); res["args"] = std::move(args); auto s = doc(); if (s != "") res.emplace("doc", stripIndentation(s)); return res; } static void _completePath(AddCompletions & completions, std::string_view prefix, bool onlyDirs) { completions.setType(Completions::Type::Filenames); #ifndef _WIN32 // TODO implement globbing completions on Windows glob_t globbuf; int flags = GLOB_NOESCAPE; #ifdef GLOB_ONLYDIR if (onlyDirs) flags |= GLOB_ONLYDIR; #endif // using expandTilde here instead of GLOB_TILDE(_CHECK) so that ~<Tab> expands to /home/user/ if (glob((expandTilde(prefix) + "*").c_str(), flags, nullptr, &globbuf) == 0) { for (size_t i = 0; i < globbuf.gl_pathc; ++i) { if (onlyDirs) { auto st = stat(globbuf.gl_pathv[i]); if (!S_ISDIR(st.st_mode)) continue; } completions.add(globbuf.gl_pathv[i]); } } globfree(&globbuf); #endif } void Args::completePath(AddCompletions & completions, size_t, std::string_view prefix) { _completePath(completions, prefix, false); } void Args::completeDir(AddCompletions & completions, size_t, std::string_view prefix) { _completePath(completions, prefix, true); } Strings argvToStrings(int argc, char * * argv) { Strings args; argc--; argv++; while (argc--) args.push_back(*argv++); return args; } std::optional<ExperimentalFeature> Command::experimentalFeature () { return { Xp::NixCommand }; } MultiCommand::MultiCommand(std::string_view commandName, const Commands & commands_) : commands(commands_) , commandName(commandName) { expectArgs({ .label = "subcommand", .optional = true, .handler = {[=,this](std::string s) { assert(!command); auto i = commands.find(s); if (i == commands.end()) { std::set<std::string> commandNames; for (auto & [name, _] : commands) commandNames.insert(name); auto suggestions = Suggestions::bestMatches(commandNames, s); throw UsageError(suggestions, "'%s' is not a recognised command", s); } command = {s, i->second()}; command->second->parent = this; }}, .completer = {[&](AddCompletions & completions, size_t, std::string_view prefix) { for (auto & [name, command] : commands) if (hasPrefix(name, prefix)) completions.add(name); }} }); categories[Command::catDefault] = "Available commands"; } bool MultiCommand::processFlag(Strings::iterator & pos, Strings::iterator end) { if (Args::processFlag(pos, end)) return true; if (command && command->second->processFlag(pos, end)) return true; return false; } bool MultiCommand::processArgs(const Strings & args, bool finish) { if (command) return command->second->processArgs(args, finish); else return Args::processArgs(args, finish); } nlohmann::json MultiCommand::toJSON() { auto cmds = nlohmann::json::object(); for (auto & [name, commandFun] : commands) { auto command = commandFun(); auto j = command->toJSON(); auto cat = nlohmann::json::object(); cat["id"] = command->category(); cat["description"] = trim(categories[command->category()]); cat["experimental-feature"] = command->experimentalFeature(); j["category"] = std::move(cat); cmds[name] = std::move(j); } auto res = Args::toJSON(); res["commands"] = std::move(cmds); return res; } }
21,234
C++
.cc
569
27.929701
148
0.548679
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,893
position.cc
NixOS_nix/src/libutil/position.cc
#include "position.hh" namespace nix { Pos::Pos(const Pos * other) { if (!other) { return; } line = other->line; column = other->column; origin = other->origin; } Pos::operator std::shared_ptr<Pos>() const { return std::make_shared<Pos>(&*this); } std::optional<LinesOfCode> Pos::getCodeLines() const { if (line == 0) return std::nullopt; if (auto source = getSource()) { LinesIterator lines(*source), end; LinesOfCode loc; if (line > 1) std::advance(lines, line - 2); if (lines != end && line > 1) loc.prevLineOfCode = *lines++; if (lines != end) loc.errLineOfCode = *lines++; if (lines != end) loc.nextLineOfCode = *lines++; return loc; } return std::nullopt; } std::optional<std::string> Pos::getSource() const { return std::visit(overloaded { [](const std::monostate &) -> std::optional<std::string> { return std::nullopt; }, [](const Pos::Stdin & s) -> std::optional<std::string> { // Get rid of the null terminators added by the parser. return std::string(s.source->c_str()); }, [](const Pos::String & s) -> std::optional<std::string> { // Get rid of the null terminators added by the parser. return std::string(s.source->c_str()); }, [](const SourcePath & path) -> std::optional<std::string> { try { return path.readFile(); } catch (Error &) { return std::nullopt; } } }, origin); } void Pos::print(std::ostream & out, bool showOrigin) const { if (showOrigin) { std::visit(overloaded { [&](const std::monostate &) { out << "«none»"; }, [&](const Pos::Stdin &) { out << "«stdin»"; }, [&](const Pos::String & s) { out << "«string»"; }, [&](const SourcePath & path) { out << path; } }, origin); out << ":"; } out << line; if (column > 0) out << ":" << column; } std::ostream & operator<<(std::ostream & str, const Pos & pos) { pos.print(str, true); return str; } void Pos::LinesIterator::bump(bool atFirst) { if (!atFirst) { pastEnd = input.empty(); if (!input.empty() && input[0] == '\r') input.remove_prefix(1); if (!input.empty() && input[0] == '\n') input.remove_prefix(1); } // nix line endings are not only \n as eg std::getline assumes, but also // \r\n **and \r alone**. not treating them all the same causes error // reports to not match with line numbers as the parser expects them. auto eol = input.find_first_of("\r\n"); if (eol > input.size()) eol = input.size(); curLine = input.substr(0, eol); input.remove_prefix(eol); } std::optional<std::string> Pos::getSnippetUpTo(const Pos & end) const { assert(this->origin == end.origin); if (end.line < this->line) return std::nullopt; if (auto source = getSource()) { auto firstLine = LinesIterator(*source); for (uint32_t i = 1; i < this->line; ++i) { ++firstLine; } auto lastLine = LinesIterator(*source); for (uint32_t i = 1; i < end.line; ++i) { ++lastLine; } LinesIterator linesEnd; std::string result; for (auto i = firstLine; i != linesEnd; ++i) { auto firstColumn = i == firstLine ? (this->column ? this->column - 1 : 0) : 0; if (firstColumn > i->size()) firstColumn = i->size(); auto lastColumn = i == lastLine ? (end.column ? end.column - 1 : 0) : std::numeric_limits<int>::max(); if (lastColumn < firstColumn) lastColumn = firstColumn; if (lastColumn > i->size()) lastColumn = i->size(); result += i->substr(firstColumn, lastColumn - firstColumn); if (i == lastLine) { break; } else { result += '\n'; } } return result; } return std::nullopt; } }
4,238
C++
.cc
131
24.343511
114
0.52713
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,894
environment-variables.cc
NixOS_nix/src/libutil/environment-variables.cc
#include "util.hh" #include "environment-variables.hh" extern char ** environ __attribute__((weak)); namespace nix { std::optional<std::string> getEnv(const std::string & key) { char * value = getenv(key.c_str()); if (!value) return {}; return std::string(value); } std::optional<std::string> getEnvNonEmpty(const std::string & key) { auto value = getEnv(key); if (value == "") return {}; return value; } std::map<std::string, std::string> getEnv() { std::map<std::string, std::string> env; for (size_t i = 0; environ[i]; ++i) { auto s = environ[i]; auto eq = strchr(s, '='); if (!eq) // invalid env, just keep going continue; env.emplace(std::string(s, eq), std::string(eq + 1)); } return env; } void clearEnv() { for (auto & name : getEnv()) unsetenv(name.first.c_str()); } void replaceEnv(const std::map<std::string, std::string> & newEnv) { clearEnv(); for (auto & newEnvVar : newEnv) setEnv(newEnvVar.first.c_str(), newEnvVar.second.c_str()); } }
1,100
C++
.cc
43
21.139535
66
0.597712
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,895
hilite.cc
NixOS_nix/src/libutil/hilite.cc
#include "hilite.hh" namespace nix { std::string hiliteMatches( std::string_view s, std::vector<std::smatch> matches, std::string_view prefix, std::string_view postfix) { // Avoid extra work on zero matches if (matches.size() == 0) return std::string(s); std::sort(matches.begin(), matches.end(), [](const auto & a, const auto & b) { return a.position() < b.position(); }); std::string out; ssize_t last_end = 0; for (auto it = matches.begin(); it != matches.end();) { auto m = *it; size_t start = m.position(); out.append(s.substr(last_end, m.position() - last_end)); // Merge continous matches ssize_t end = start + m.length(); while (++it != matches.end() && (*it).position() <= end) { auto n = *it; ssize_t nend = start + (n.position() - start + n.length()); if (nend > end) end = nend; } out.append(prefix); out.append(s.substr(start, end - start)); out.append(postfix); last_end = end; } out.append(s.substr(last_end)); return out; } }
1,161
C++
.cc
37
24.459459
82
0.549687
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
10,896
error.cc
NixOS_nix/src/libutil/error.cc
#include <algorithm> #include "error.hh" #include "environment-variables.hh" #include "signals.hh" #include "terminal.hh" #include "position.hh" #include <iostream> #include <optional> #include "serialise.hh" #include <sstream> namespace nix { void BaseError::addTrace(std::shared_ptr<Pos> && e, HintFmt hint, TracePrint print) { err.traces.push_front(Trace { .pos = std::move(e), .hint = hint, .print = print }); } void throwExceptionSelfCheck() { // This is meant to be caught in initLibUtil() throw Error("C++ exception handling is broken. This would appear to be a problem with the way Nix was compiled and/or linked and/or loaded."); } // c++ std::exception descendants must have a 'const char* what()' function. // This stringifies the error and caches it for use by what(), or similarly by msg(). const std::string & BaseError::calcWhat() const { if (what_.has_value()) return *what_; else { std::ostringstream oss; showErrorInfo(oss, err, loggerSettings.showTrace); what_ = oss.str(); return *what_; } } std::optional<std::string> ErrorInfo::programName = std::nullopt; std::ostream & operator <<(std::ostream & os, const HintFmt & hf) { return os << hf.str(); } /** * An arbitrarily defined value comparison for the purpose of using traces in the key of a sorted container. */ inline std::strong_ordering operator<=>(const Trace& lhs, const Trace& rhs) { // `std::shared_ptr` does not have value semantics for its comparison // functions, so we need to check for nulls and compare the dereferenced // values here. if (lhs.pos != rhs.pos) { if (auto cmp = bool{lhs.pos} <=> bool{rhs.pos}; cmp != 0) return cmp; if (auto cmp = *lhs.pos <=> *rhs.pos; cmp != 0) return cmp; } // This formats a freshly formatted hint string and then throws it away, which // shouldn't be much of a problem because it only runs when pos is equal, and this function is // used for trace printing, which is infrequent. return lhs.hint.str() <=> rhs.hint.str(); } // print lines of code to the ostream, indicating the error column. void printCodeLines(std::ostream & out, const std::string & prefix, const Pos & errPos, const LinesOfCode & loc) { // previous line of code. if (loc.prevLineOfCode.has_value()) { out << std::endl << fmt("%1% %|2$5d|| %3%", prefix, (errPos.line - 1), *loc.prevLineOfCode); } if (loc.errLineOfCode.has_value()) { // line of code containing the error. out << std::endl << fmt("%1% %|2$5d|| %3%", prefix, (errPos.line), *loc.errLineOfCode); // error arrows for the column range. if (errPos.column > 0) { int start = errPos.column; std::string spaces; for (int i = 0; i < start; ++i) { spaces.append(" "); } std::string arrows("^"); out << std::endl << fmt("%1% |%2%" ANSI_RED "%3%" ANSI_NORMAL, prefix, spaces, arrows); } } // next line of code. if (loc.nextLineOfCode.has_value()) { out << std::endl << fmt("%1% %|2$5d|| %3%", prefix, (errPos.line + 1), *loc.nextLineOfCode); } } static std::string indent(std::string_view indentFirst, std::string_view indentRest, std::string_view s) { std::string res; bool first = true; while (!s.empty()) { auto end = s.find('\n'); if (!first) res += "\n"; res += chomp(std::string(first ? indentFirst : indentRest) + std::string(s.substr(0, end))); first = false; if (end == s.npos) break; s = s.substr(end + 1); } return res; } /** * A development aid for finding missing positions, to improve error messages. Example use: * * _NIX_EVAL_SHOW_UNKNOWN_LOCATIONS=1 _NIX_TEST_ACCEPT=1 make tests/lang.sh.test * git diff -U20 tests * */ static bool printUnknownLocations = getEnv("_NIX_EVAL_SHOW_UNKNOWN_LOCATIONS").has_value(); /** * Print a position, if it is known. * * @return true if a position was printed. */ static bool printPosMaybe(std::ostream & oss, std::string_view indent, const std::shared_ptr<Pos> & pos) { bool hasPos = pos && *pos; if (hasPos) { oss << indent << ANSI_BLUE << "at " ANSI_WARNING << *pos << ANSI_NORMAL << ":"; if (auto loc = pos->getCodeLines()) { printCodeLines(oss, "", *pos, *loc); oss << "\n"; } } else if (printUnknownLocations) { oss << "\n" << indent << ANSI_BLUE << "at " ANSI_RED << "UNKNOWN LOCATION" << ANSI_NORMAL << "\n"; } return hasPos; } static void printTrace( std::ostream & output, const std::string_view & indent, size_t & count, const Trace & trace) { output << "\n" << "… " << trace.hint.str() << "\n"; if (printPosMaybe(output, indent, trace.pos)) count++; } void printSkippedTracesMaybe( std::ostream & output, const std::string_view & indent, size_t & count, std::vector<Trace> & skippedTraces, std::set<Trace> tracesSeen) { if (skippedTraces.size() > 0) { // If we only skipped a few frames, print them out normally; // messages like "1 duplicate frames omitted" aren't helpful. if (skippedTraces.size() <= 5) { for (auto & trace : skippedTraces) { printTrace(output, indent, count, trace); } } else { output << "\n" << ANSI_WARNING "(" << skippedTraces.size() << " duplicate frames omitted)" ANSI_NORMAL << "\n"; // Clear the set of "seen" traces after printing a chunk of // `duplicate frames omitted`. // // Consider a mutually recursive stack trace with: // - 10 entries of A // - 10 entries of B // - 10 entries of A // // If we don't clear `tracesSeen` here, we would print output like this: // - 1 entry of A // - (9 duplicate frames omitted) // - 1 entry of B // - (19 duplicate frames omitted) // // This would obscure the control flow, which went from A, // to B, and back to A again. // // In contrast, if we do clear `tracesSeen`, the output looks like this: // - 1 entry of A // - (9 duplicate frames omitted) // - 1 entry of B // - (9 duplicate frames omitted) // - 1 entry of A // - (9 duplicate frames omitted) // // See: `tests/functional/lang/eval-fail-mutual-recursion.nix` tracesSeen.clear(); } } // We've either printed each trace in `skippedTraces` normally, or // printed a chunk of `duplicate frames omitted`. Either way, we've // processed these traces and can clear them. skippedTraces.clear(); } std::ostream & showErrorInfo(std::ostream & out, const ErrorInfo & einfo, bool showTrace) { std::string prefix; switch (einfo.level) { case Verbosity::lvlError: { prefix = ANSI_RED "error"; break; } case Verbosity::lvlNotice: { prefix = ANSI_RED "note"; break; } case Verbosity::lvlWarn: { if (einfo.isFromExpr) prefix = ANSI_WARNING "evaluation warning"; else prefix = ANSI_WARNING "warning"; break; } case Verbosity::lvlInfo: { prefix = ANSI_GREEN "info"; break; } case Verbosity::lvlTalkative: { prefix = ANSI_GREEN "talk"; break; } case Verbosity::lvlChatty: { prefix = ANSI_GREEN "chat"; break; } case Verbosity::lvlVomit: { prefix = ANSI_GREEN "vomit"; break; } case Verbosity::lvlDebug: { prefix = ANSI_WARNING "debug"; break; } default: assert(false); } // FIXME: show the program name as part of the trace? if (einfo.programName && einfo.programName != ErrorInfo::programName) prefix += fmt(" [%s]:" ANSI_NORMAL " ", einfo.programName.value_or("")); else prefix += ":" ANSI_NORMAL " "; std::ostringstream oss; /* * Traces * ------ * * The semantics of traces is a bit weird. We have only one option to * print them and to make them verbose (--show-trace). In the code they * are always collected, but they are not printed by default. The code * also collects more traces when the option is on. This means that there * is no way to print the simplified traces at all. * * I (layus) designed the code to attach positions to a restricted set of * messages. This means that we have a lot of traces with no position at * all, including most of the base error messages. For example "type * error: found a string while a set was expected" has no position, but * will come with several traces detailing it's precise relation to the * closest know position. This makes erroring without printing traces * quite useless. * * This is why I introduced the idea to always print a few traces on * error. The number 3 is quite arbitrary, and was selected so as not to * clutter the console on error. For the same reason, a trace with an * error position takes more space, and counts as two traces towards the * limit. * * The rest is truncated, unless --show-trace is passed. This preserves * the same bad semantics of --show-trace to both show the trace and * augment it with new data. Not too sure what is the best course of * action. * * The issue is that it is fundamentally hard to provide a trace for a * lazy language. The trace will only cover the current spine of the * evaluation, missing things that have been evaluated before. For * example, most type errors are hard to inspect because there is not * trace for the faulty value. These errors should really print the faulty * value itself. * * In function calls, the --show-trace flag triggers extra traces for each * function invocation. These work as scopes, allowing to follow the * current spine of the evaluation graph. Without that flag, the error * trace should restrict itself to a restricted prefix of that trace, * until the first scope. If we ever get to such a precise error * reporting, there would be no need to add an arbitrary limit here. We * could always print the full trace, and it would just be small without * the flag. * * One idea I had is for XxxError.addTrace() to perform nothing if one * scope has already been traced. Alternatively, we could stop here when * we encounter such a scope instead of after an arbitrary number of * traces. This however requires to augment traces with the notion of * "scope". * * This is particularly visible in code like evalAttrs(...) where we have * to make a decision between the two following options. * * ``` long traces * inline void EvalState::evalAttrs(Env & env, Expr * e, Value & v, const Pos & pos, std::string_view errorCtx) * { * try { * e->eval(*this, env, v); * if (v.type() != nAttrs) * error<TypeError>("expected a set but found %1%", v); * } catch (Error & e) { * e.addTrace(pos, errorCtx); * throw; * } * } * ``` * * ``` short traces * inline void EvalState::evalAttrs(Env & env, Expr * e, Value & v, const Pos & pos, std::string_view errorCtx) * { * e->eval(*this, env, v); * try { * if (v.type() != nAttrs) * error<TypeError>("expected a set but found %1%", v); * } catch (Error & e) { * e.addTrace(pos, errorCtx); * throw; * } * } * ``` * * The second example can be rewritten more concisely, but kept in this * form to highlight the symmetry. The first option adds more information, * because whatever caused an error down the line, in the generic eval * function, will get annotated with the code location that uses and * required it. The second option is less verbose, but does not provide * any context at all as to where and why a failing value was required. * * Scopes would fix that, by adding context only when --show-trace is * passed, and keeping the trace terse otherwise. * */ // Enough indent to align with with the `... ` // prepended to each element of the trace auto ellipsisIndent = " "; if (!einfo.traces.empty()) { // Stack traces seen since we last printed a chunk of `duplicate frames // omitted`. std::set<Trace> tracesSeen; // A consecutive sequence of stack traces that are all in `tracesSeen`. std::vector<Trace> skippedTraces; size_t count = 0; bool truncate = false; for (const auto & trace : einfo.traces) { if (trace.hint.str().empty()) continue; if (!showTrace && count > 3) { truncate = true; } if (!truncate || trace.print == TracePrint::Always) { if (tracesSeen.count(trace)) { skippedTraces.push_back(trace); continue; } tracesSeen.insert(trace); printSkippedTracesMaybe(oss, ellipsisIndent, count, skippedTraces, tracesSeen); count++; printTrace(oss, ellipsisIndent, count, trace); } } printSkippedTracesMaybe(oss, ellipsisIndent, count, skippedTraces, tracesSeen); if (truncate) { oss << "\n" << ANSI_WARNING "(stack trace truncated; use '--show-trace' to show the full, detailed trace)" ANSI_NORMAL << "\n"; } oss << "\n" << prefix; } oss << einfo.msg << "\n"; printPosMaybe(oss, "", einfo.pos); auto suggestions = einfo.suggestions.trim(); if (!suggestions.suggestions.empty()) { oss << "Did you mean " << suggestions.trim() << "?" << std::endl; } out << indent(prefix, std::string(filterANSIEscapes(prefix, true).size(), ' '), chomp(oss.str())); return out; } /** Write to stderr in a robust and minimal way, considering that the process * may be in a bad state. */ static void writeErr(std::string_view buf) { while (!buf.empty()) { auto n = write(STDERR_FILENO, buf.data(), buf.size()); if (n < 0) { if (errno == EINTR) continue; abort(); } buf = buf.substr(n); } } void panic(std::string_view msg) { writeErr("\n\n" ANSI_RED "terminating due to unexpected unrecoverable internal error: " ANSI_NORMAL ); writeErr(msg); writeErr("\n"); abort(); } void panic(const char * file, int line, const char * func) { char buf[512]; int n = snprintf(buf, sizeof(buf), "Unexpected condition in %s at %s:%d", func, file, line); if (n < 0) panic("Unexpected condition and could not format error message"); panic(std::string_view(buf, std::min(static_cast<int>(sizeof(buf)), n))); } }
15,822
C++
.cc
417
30.601918
146
0.589189
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,897
compute-levels.cc
NixOS_nix/src/libutil/compute-levels.cc
#include "types.hh" #if HAVE_LIBCPUID #include <libcpuid/libcpuid.h> #endif namespace nix { #if HAVE_LIBCPUID StringSet computeLevels() { StringSet levels; if (!cpuid_present()) return levels; cpu_raw_data_t raw; cpu_id_t data; if (cpuid_get_raw_data(&raw) < 0) return levels; if (cpu_identify(&raw, &data) < 0) return levels; if (!(data.flags[CPU_FEATURE_CMOV] && data.flags[CPU_FEATURE_CX8] && data.flags[CPU_FEATURE_FPU] && data.flags[CPU_FEATURE_FXSR] && data.flags[CPU_FEATURE_MMX] && data.flags[CPU_FEATURE_SSE] && data.flags[CPU_FEATURE_SSE2])) return levels; levels.insert("x86_64-v1"); if (!(data.flags[CPU_FEATURE_CX16] && data.flags[CPU_FEATURE_LAHF_LM] && data.flags[CPU_FEATURE_POPCNT] && // SSE3 data.flags[CPU_FEATURE_PNI] && data.flags[CPU_FEATURE_SSSE3] && data.flags[CPU_FEATURE_SSE4_1] && data.flags[CPU_FEATURE_SSE4_2])) return levels; levels.insert("x86_64-v2"); if (!(data.flags[CPU_FEATURE_AVX] && data.flags[CPU_FEATURE_AVX2] && data.flags[CPU_FEATURE_F16C] && data.flags[CPU_FEATURE_FMA3] && // LZCNT data.flags[CPU_FEATURE_ABM] && data.flags[CPU_FEATURE_MOVBE])) return levels; levels.insert("x86_64-v3"); if (!(data.flags[CPU_FEATURE_AVX512F] && data.flags[CPU_FEATURE_AVX512BW] && data.flags[CPU_FEATURE_AVX512CD] && data.flags[CPU_FEATURE_AVX512DQ] && data.flags[CPU_FEATURE_AVX512VL])) return levels; levels.insert("x86_64-v4"); return levels; } #else StringSet computeLevels() { return StringSet{}; } #endif // HAVE_LIBCPUID }
1,875
C++
.cc
59
23.711864
47
0.580501
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,898
unix-domain-socket.cc
NixOS_nix/src/libutil/unix-domain-socket.cc
#include "file-system.hh" #include "unix-domain-socket.hh" #include "util.hh" #ifdef _WIN32 # include <winsock2.h> # include <afunix.h> #else # include <sys/socket.h> # include <sys/un.h> # include "processes.hh" #endif #include <unistd.h> namespace nix { AutoCloseFD createUnixDomainSocket() { AutoCloseFD fdSocket = toDescriptor(socket(PF_UNIX, SOCK_STREAM #ifdef SOCK_CLOEXEC | SOCK_CLOEXEC #endif , 0)); if (!fdSocket) throw SysError("cannot create Unix domain socket"); #ifndef _WIN32 unix::closeOnExec(fdSocket.get()); #endif return fdSocket; } AutoCloseFD createUnixDomainSocket(const Path & path, mode_t mode) { auto fdSocket = nix::createUnixDomainSocket(); bind(fdSocket.get(), path); if (chmod(path.c_str(), mode) == -1) throw SysError("changing permissions on '%1%'", path); if (listen(toSocket(fdSocket.get()), 100) == -1) throw SysError("cannot listen on socket '%1%'", path); return fdSocket; } static void bindConnectProcHelper( std::string_view operationName, auto && operation, Socket fd, const std::string & path) { struct sockaddr_un addr; addr.sun_family = AF_UNIX; // Casting between types like these legacy C library interfaces // require is forbidden in C++. To maintain backwards // compatibility, the implementation of the bind/connect functions // contains some hints to the compiler that allow for this // special case. auto * psaddr = reinterpret_cast<struct sockaddr *>(&addr); if (path.size() + 1 >= sizeof(addr.sun_path)) { #ifdef _WIN32 throw Error("cannot %s to socket at '%s': path is too long", operationName, path); #else Pipe pipe; pipe.create(); Pid pid = startProcess([&] { try { pipe.readSide.close(); Path dir = dirOf(path); if (chdir(dir.c_str()) == -1) throw SysError("chdir to '%s' failed", dir); std::string base(baseNameOf(path)); if (base.size() + 1 >= sizeof(addr.sun_path)) throw Error("socket path '%s' is too long", base); memcpy(addr.sun_path, base.c_str(), base.size() + 1); if (operation(fd, psaddr, sizeof(addr)) == -1) throw SysError("cannot %s to socket at '%s'", operationName, path); writeFull(pipe.writeSide.get(), "0\n"); } catch (SysError & e) { writeFull(pipe.writeSide.get(), fmt("%d\n", e.errNo)); } catch (...) { writeFull(pipe.writeSide.get(), "-1\n"); } }); pipe.writeSide.close(); auto errNo = string2Int<int>(chomp(drainFD(pipe.readSide.get()))); if (!errNo || *errNo == -1) throw Error("cannot %s to socket at '%s'", operationName, path); else if (*errNo > 0) { errno = *errNo; throw SysError("cannot %s to socket at '%s'", operationName, path); } #endif } else { memcpy(addr.sun_path, path.c_str(), path.size() + 1); if (operation(fd, psaddr, sizeof(addr)) == -1) throw SysError("cannot %s to socket at '%s'", operationName, path); } } void bind(Socket fd, const std::string & path) { unlink(path.c_str()); bindConnectProcHelper("bind", ::bind, fd, path); } void connect(Socket fd, const std::string & path) { bindConnectProcHelper("connect", ::connect, fd, path); } }
3,528
C++
.cc
99
28.717172
90
0.599531
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,899
file-system.cc
NixOS_nix/src/libutil/file-system.cc
#include "environment-variables.hh" #include "file-system.hh" #include "file-path.hh" #include "file-path-impl.hh" #include "signals.hh" #include "finally.hh" #include "serialise.hh" #include "util.hh" #include <atomic> #include <cerrno> #include <climits> #include <cstdio> #include <cstdlib> #include <deque> #include <sstream> #include <filesystem> #include <fcntl.h> #include <sys/types.h> #include <sys/time.h> #include <unistd.h> #ifdef _WIN32 # include <io.h> #endif #include "strings-inline.hh" namespace nix { namespace fs { using namespace std::filesystem; } /** * Treat the string as possibly an absolute path, by inspecting the * start of it. Return whether it was probably intended to be * absolute. */ static bool isAbsolute(PathView path) { return fs::path { path }.is_absolute(); } Path absPath(PathView path, std::optional<PathView> dir, bool resolveSymlinks) { std::string scratch; if (!isAbsolute(path)) { // In this case we need to call `canonPath` on a newly-created // string. We set `scratch` to that string first, and then set // `path` to `scratch`. This ensures the newly-created string // lives long enough for the call to `canonPath`, and allows us // to just accept a `std::string_view`. if (!dir) { #ifdef __GNU__ /* GNU (aka. GNU/Hurd) doesn't have any limitation on path lengths and doesn't define `PATH_MAX'. */ char *buf = getcwd(NULL, 0); if (buf == NULL) #else char buf[PATH_MAX]; if (!getcwd(buf, sizeof(buf))) #endif throw SysError("cannot get cwd"); scratch = concatStrings(buf, "/", path); #ifdef __GNU__ free(buf); #endif } else scratch = concatStrings(*dir, "/", path); path = scratch; } return canonPath(path, resolveSymlinks); } std::filesystem::path absPath(const std::filesystem::path & path, bool resolveSymlinks) { return absPath(path.string(), std::nullopt, resolveSymlinks); } Path canonPath(PathView path, bool resolveSymlinks) { assert(path != ""); if (!isAbsolute(path)) throw Error("not an absolute path: '%1%'", path); // For Windows auto rootName = fs::path { path }.root_name(); /* This just exists because we cannot set the target of `remaining` (the callback parameter) directly to a newly-constructed string, since it is `std::string_view`. */ std::string temp; /* Count the number of times we follow a symlink and stop at some arbitrary (but high) limit to prevent infinite loops. */ unsigned int followCount = 0, maxFollow = 1024; auto ret = canonPathInner<OsPathTrait<char>>( path, [&followCount, &temp, maxFollow, resolveSymlinks] (std::string & result, std::string_view & remaining) { if (resolveSymlinks && fs::is_symlink(result)) { if (++followCount >= maxFollow) throw Error("infinite symlink recursion in path '%0%'", remaining); remaining = (temp = concatStrings(readLink(result), remaining)); if (isAbsolute(remaining)) { /* restart for symlinks pointing to absolute path */ result.clear(); } else { result = dirOf(result); if (result == "/") { /* we don’t want trailing slashes here, which `dirOf` only produces if `result = /` */ result.clear(); } } } }); if (!rootName.empty()) ret = rootName.string() + std::move(ret); return ret; } Path dirOf(const PathView path) { Path::size_type pos = OsPathTrait<char>::rfindPathSep(path); if (pos == path.npos) return "."; return fs::path{path}.parent_path().string(); } std::string_view baseNameOf(std::string_view path) { if (path.empty()) return ""; auto last = path.size() - 1; while (last > 0 && OsPathTrait<char>::isPathSep(path[last])) last -= 1; auto pos = OsPathTrait<char>::rfindPathSep(path, last); if (pos == path.npos) pos = 0; else pos += 1; return path.substr(pos, last - pos + 1); } bool isInDir(std::string_view path, std::string_view dir) { return path.substr(0, 1) == "/" && path.substr(0, dir.size()) == dir && path.size() >= dir.size() + 2 && path[dir.size()] == '/'; } bool isDirOrInDir(std::string_view path, std::string_view dir) { return path == dir || isInDir(path, dir); } struct stat stat(const Path & path) { struct stat st; if (stat(path.c_str(), &st)) throw SysError("getting status of '%1%'", path); return st; } #ifdef _WIN32 # define STAT stat #else # define STAT lstat #endif struct stat lstat(const Path & path) { struct stat st; if (STAT(path.c_str(), &st)) throw SysError("getting status of '%1%'", path); return st; } std::optional<struct stat> maybeLstat(const Path & path) { std::optional<struct stat> st{std::in_place}; if (STAT(path.c_str(), &*st)) { if (errno == ENOENT || errno == ENOTDIR) st.reset(); else throw SysError("getting status of '%s'", path); } return st; } bool pathExists(const Path & path) { return maybeLstat(path).has_value(); } bool pathAccessible(const std::filesystem::path & path) { try { return pathExists(path.string()); } catch (SysError & e) { // swallow EPERM if (e.errNo == EPERM) return false; throw; } } Path readLink(const Path & path) { checkInterrupt(); return fs::read_symlink(path).string(); } std::string readFile(const Path & path) { AutoCloseFD fd = toDescriptor(open(path.c_str(), O_RDONLY // TODO #ifndef _WIN32 | O_CLOEXEC #endif )); if (!fd) throw SysError("opening file '%1%'", path); return readFile(fd.get()); } std::string readFile(const std::filesystem::path & path) { return readFile(os_string_to_string(PathViewNG { path })); } void readFile(const Path & path, Sink & sink) { AutoCloseFD fd = toDescriptor(open(path.c_str(), O_RDONLY // TODO #ifndef _WIN32 | O_CLOEXEC #endif )); if (!fd) throw SysError("opening file '%s'", path); drainFD(fd.get(), sink); } void writeFile(const Path & path, std::string_view s, mode_t mode, bool sync) { AutoCloseFD fd = toDescriptor(open(path.c_str(), O_WRONLY | O_TRUNC | O_CREAT // TODO #ifndef _WIN32 | O_CLOEXEC #endif , mode)); if (!fd) throw SysError("opening file '%1%'", path); try { writeFull(fd.get(), s); } catch (Error & e) { e.addTrace({}, "writing file '%1%'", path); throw; } if (sync) fd.fsync(); // Explicitly close to make sure exceptions are propagated. fd.close(); if (sync) syncParent(path); } void writeFile(const Path & path, Source & source, mode_t mode, bool sync) { AutoCloseFD fd = toDescriptor(open(path.c_str(), O_WRONLY | O_TRUNC | O_CREAT // TODO #ifndef _WIN32 | O_CLOEXEC #endif , mode)); if (!fd) throw SysError("opening file '%1%'", path); std::array<char, 64 * 1024> buf; try { while (true) { try { auto n = source.read(buf.data(), buf.size()); writeFull(fd.get(), {buf.data(), n}); } catch (EndOfFile &) { break; } } } catch (Error & e) { e.addTrace({}, "writing file '%1%'", path); throw; } if (sync) fd.fsync(); // Explicitly close to make sure exceptions are propagated. fd.close(); if (sync) syncParent(path); } void syncParent(const Path & path) { AutoCloseFD fd = toDescriptor(open(dirOf(path).c_str(), O_RDONLY, 0)); if (!fd) throw SysError("opening file '%1%'", path); fd.fsync(); } void recursiveSync(const Path & path) { /* If it's a file, just fsync and return. */ auto st = lstat(path); if (S_ISREG(st.st_mode)) { AutoCloseFD fd = toDescriptor(open(path.c_str(), O_RDONLY, 0)); if (!fd) throw SysError("opening file '%1%'", path); fd.fsync(); return; } /* Otherwise, perform a depth-first traversal of the directory and fsync all the files. */ std::deque<fs::path> dirsToEnumerate; dirsToEnumerate.push_back(path); std::vector<fs::path> dirsToFsync; while (!dirsToEnumerate.empty()) { auto currentDir = dirsToEnumerate.back(); dirsToEnumerate.pop_back(); for (auto & entry : std::filesystem::directory_iterator(currentDir)) { auto st = entry.symlink_status(); if (fs::is_directory(st)) { dirsToEnumerate.emplace_back(entry.path()); } else if (fs::is_regular_file(st)) { AutoCloseFD fd = toDescriptor(open(entry.path().string().c_str(), O_RDONLY, 0)); if (!fd) throw SysError("opening file '%1%'", entry.path()); fd.fsync(); } } dirsToFsync.emplace_back(std::move(currentDir)); } /* Fsync all the directories. */ for (auto dir = dirsToFsync.rbegin(); dir != dirsToFsync.rend(); ++dir) { AutoCloseFD fd = toDescriptor(open(dir->string().c_str(), O_RDONLY, 0)); if (!fd) throw SysError("opening directory '%1%'", *dir); fd.fsync(); } } static void _deletePath(Descriptor parentfd, const fs::path & path, uint64_t & bytesFreed) { #ifndef _WIN32 checkInterrupt(); std::string name(baseNameOf(path.native())); struct stat st; if (fstatat(parentfd, name.c_str(), &st, AT_SYMLINK_NOFOLLOW) == -1) { if (errno == ENOENT) return; throw SysError("getting status of '%1%'", path); } if (!S_ISDIR(st.st_mode)) { /* We are about to delete a file. Will it likely free space? */ switch (st.st_nlink) { /* Yes: last link. */ case 1: bytesFreed += st.st_size; break; /* Maybe: yes, if 'auto-optimise-store' or manual optimisation was performed. Instead of checking for real let's assume it's an optimised file and space will be freed. In worst case we will double count on freed space for files with exactly two hardlinks for unoptimised packages. */ case 2: bytesFreed += st.st_size; break; /* No: 3+ links. */ default: break; } } if (S_ISDIR(st.st_mode)) { /* Make the directory accessible. */ const auto PERM_MASK = S_IRUSR | S_IWUSR | S_IXUSR; if ((st.st_mode & PERM_MASK) != PERM_MASK) { if (fchmodat(parentfd, name.c_str(), st.st_mode | PERM_MASK, 0) == -1) throw SysError("chmod '%1%'", path); } int fd = openat(parentfd, path.c_str(), O_RDONLY); if (fd == -1) throw SysError("opening directory '%1%'", path); AutoCloseDir dir(fdopendir(fd)); if (!dir) throw SysError("opening directory '%1%'", path); struct dirent * dirent; while (errno = 0, dirent = readdir(dir.get())) { /* sic */ checkInterrupt(); std::string childName = dirent->d_name; if (childName == "." || childName == "..") continue; _deletePath(dirfd(dir.get()), path + "/" + childName, bytesFreed); } if (errno) throw SysError("reading directory '%1%'", path); } int flags = S_ISDIR(st.st_mode) ? AT_REMOVEDIR : 0; if (unlinkat(parentfd, name.c_str(), flags) == -1) { if (errno == ENOENT) return; throw SysError("cannot unlink '%1%'", path); } #else // TODO implement throw UnimplementedError("_deletePath"); #endif } static void _deletePath(const fs::path & path, uint64_t & bytesFreed) { Path dir = dirOf(path.string()); if (dir == "") dir = "/"; AutoCloseFD dirfd = toDescriptor(open(dir.c_str(), O_RDONLY)); if (!dirfd) { if (errno == ENOENT) return; throw SysError("opening directory '%1%'", path); } _deletePath(dirfd.get(), path, bytesFreed); } void deletePath(const fs::path & path) { uint64_t dummy; deletePath(path, dummy); } void createDir(const Path & path, mode_t mode) { if (mkdir(path.c_str() #ifndef _WIN32 , mode #endif ) == -1) throw SysError("creating directory '%1%'", path); } void createDirs(const Path & path) { try { fs::create_directories(path); } catch (fs::filesystem_error & e) { throw SysError("creating directory '%1%'", path); } } void deletePath(const fs::path & path, uint64_t & bytesFreed) { //Activity act(*logger, lvlDebug, "recursively deleting path '%1%'", path); bytesFreed = 0; _deletePath(path, bytesFreed); } ////////////////////////////////////////////////////////////////////// AutoDelete::AutoDelete() : del{false} {} AutoDelete::AutoDelete(const std::filesystem::path & p, bool recursive) : _path(p) { del = true; this->recursive = recursive; } AutoDelete::~AutoDelete() { try { if (del) { if (recursive) deletePath(_path); else { fs::remove(_path); } } } catch (...) { ignoreExceptionInDestructor(); } } void AutoDelete::cancel() { del = false; } void AutoDelete::reset(const fs::path & p, bool recursive) { _path = p; this->recursive = recursive; del = true; } ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// std::string defaultTempDir() { return getEnvNonEmpty("TMPDIR").value_or("/tmp"); } static Path tempName(Path tmpRoot, const Path & prefix, bool includePid, std::atomic<unsigned int> & counter) { tmpRoot = canonPath(tmpRoot.empty() ? defaultTempDir() : tmpRoot, true); if (includePid) return fmt("%1%/%2%-%3%-%4%", tmpRoot, prefix, getpid(), counter++); else return fmt("%1%/%2%-%3%", tmpRoot, prefix, counter++); } Path createTempDir(const Path & tmpRoot, const Path & prefix, bool includePid, bool useGlobalCounter, mode_t mode) { static std::atomic<unsigned int> globalCounter = 0; std::atomic<unsigned int> localCounter = 0; auto & counter(useGlobalCounter ? globalCounter : localCounter); while (1) { checkInterrupt(); Path tmpDir = tempName(tmpRoot, prefix, includePid, counter); if (mkdir(tmpDir.c_str() #ifndef _WIN32 // TODO abstract mkdir perms for Windows , mode #endif ) == 0) { #if __FreeBSD__ /* Explicitly set the group of the directory. This is to work around around problems caused by BSD's group ownership semantics (directories inherit the group of the parent). For instance, the group of /tmp on FreeBSD is "wheel", so all directories created in /tmp will be owned by "wheel"; but if the user is not in "wheel", then "tar" will fail to unpack archives that have the setgid bit set on directories. */ if (chown(tmpDir.c_str(), (uid_t) -1, getegid()) != 0) throw SysError("setting group of directory '%1%'", tmpDir); #endif return tmpDir; } if (errno != EEXIST) throw SysError("creating directory '%1%'", tmpDir); } } std::pair<AutoCloseFD, Path> createTempFile(const Path & prefix) { Path tmpl(defaultTempDir() + "/" + prefix + ".XXXXXX"); // Strictly speaking, this is UB, but who cares... // FIXME: use O_TMPFILE. AutoCloseFD fd = toDescriptor(mkstemp((char *) tmpl.c_str())); if (!fd) throw SysError("creating temporary file '%s'", tmpl); #ifndef _WIN32 unix::closeOnExec(fd.get()); #endif return {std::move(fd), tmpl}; } void createSymlink(const Path & target, const Path & link) { fs::create_symlink(target, link); } void replaceSymlink(const fs::path & target, const fs::path & link) { for (unsigned int n = 0; true; n++) { auto tmp = link.parent_path() / fs::path{fmt(".%d_%s", n, link.filename().string())}; tmp = tmp.lexically_normal(); try { fs::create_symlink(target, tmp); } catch (fs::filesystem_error & e) { if (e.code() == std::errc::file_exists) continue; throw; } fs::rename(tmp, link); break; } } void setWriteTime( const fs::path & path, time_t accessedTime, time_t modificationTime, std::optional<bool> optIsSymlink) { #ifdef _WIN32 // FIXME use `fs::last_write_time`. // // Would be nice to use std::filesystem unconditionally, but // doesn't support access time just modification time. // // System clock vs File clock issues also make that annoying. warn("Changing file times is not yet implemented on Windows, path is '%s'", path); #elif HAVE_UTIMENSAT && HAVE_DECL_AT_SYMLINK_NOFOLLOW struct timespec times[2] = { { .tv_sec = accessedTime, .tv_nsec = 0, }, { .tv_sec = modificationTime, .tv_nsec = 0, }, }; if (utimensat(AT_FDCWD, path.c_str(), times, AT_SYMLINK_NOFOLLOW) == -1) throw SysError("changing modification time of '%s' (using `utimensat`)", path); #else struct timeval times[2] = { { .tv_sec = accessedTime, .tv_usec = 0, }, { .tv_sec = modificationTime, .tv_usec = 0, }, }; #if HAVE_LUTIMES if (lutimes(path.c_str(), times) == -1) throw SysError("changing modification time of '%s'", path); #else bool isSymlink = optIsSymlink ? *optIsSymlink : fs::is_symlink(path); if (!isSymlink) { if (utimes(path.c_str(), times) == -1) throw SysError("changing modification time of '%s' (not a symlink)", path); } else { throw Error("Cannot modification time of symlink '%s'", path); } #endif #endif } void setWriteTime(const fs::path & path, const struct stat & st) { setWriteTime(path, st.st_atime, st.st_mtime, S_ISLNK(st.st_mode)); } void copyFile(const fs::path & from, const fs::path & to, bool andDelete) { auto fromStatus = fs::symlink_status(from); // Mark the directory as writable so that we can delete its children if (andDelete && fs::is_directory(fromStatus)) { fs::permissions(from, fs::perms::owner_write, fs::perm_options::add | fs::perm_options::nofollow); } if (fs::is_symlink(fromStatus) || fs::is_regular_file(fromStatus)) { fs::copy(from, to, fs::copy_options::copy_symlinks | fs::copy_options::overwrite_existing); } else if (fs::is_directory(fromStatus)) { fs::create_directory(to); for (auto & entry : fs::directory_iterator(from)) { copyFile(entry, to / entry.path().filename(), andDelete); } } else { throw Error("file '%s' has an unsupported type", from); } setWriteTime(to, lstat(from.string().c_str())); if (andDelete) { if (!fs::is_symlink(fromStatus)) fs::permissions(from, fs::perms::owner_write, fs::perm_options::add | fs::perm_options::nofollow); fs::remove(from); } } void moveFile(const Path & oldName, const Path & newName) { try { std::filesystem::rename(oldName, newName); } catch (fs::filesystem_error & e) { auto oldPath = fs::path(oldName); auto newPath = fs::path(newName); // For the move to be as atomic as possible, copy to a temporary // directory fs::path temp = createTempDir( os_string_to_string(PathViewNG { newPath.parent_path() }), "rename-tmp"); Finally removeTemp = [&]() { fs::remove(temp); }; auto tempCopyTarget = temp / "copy-target"; if (e.code().value() == EXDEV) { fs::remove(newPath); warn("Can’t rename %s as %s, copying instead", oldName, newName); copyFile(oldPath, tempCopyTarget, true); std::filesystem::rename( os_string_to_string(PathViewNG { tempCopyTarget }), os_string_to_string(PathViewNG { newPath })); } } } ////////////////////////////////////////////////////////////////////// bool isExecutableFileAmbient(const fs::path & exe) { // Check file type, because directory being executable means // something completely different. // `is_regular_file` follows symlinks before checking. return std::filesystem::is_regular_file(exe) && access(exe.string().c_str(), #ifdef WIN32 0 // TODO do better #else X_OK #endif ) == 0; } }
21,268
C++
.cc
650
26.144615
110
0.582708
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,900
file-content-address.cc
NixOS_nix/src/libutil/file-content-address.cc
#include "file-content-address.hh" #include "archive.hh" #include "git.hh" #include "source-path.hh" namespace nix { static std::optional<FileSerialisationMethod> parseFileSerialisationMethodOpt(std::string_view input) { if (input == "flat") { return FileSerialisationMethod::Flat; } else if (input == "nar") { return FileSerialisationMethod::NixArchive; } else { return std::nullopt; } } FileSerialisationMethod parseFileSerialisationMethod(std::string_view input) { auto ret = parseFileSerialisationMethodOpt(input); if (ret) return *ret; else throw UsageError("Unknown file serialiation method '%s', expect `flat` or `nar`"); } FileIngestionMethod parseFileIngestionMethod(std::string_view input) { if (input == "git") { return FileIngestionMethod::Git; } else { auto ret = parseFileSerialisationMethodOpt(input); if (ret) return static_cast<FileIngestionMethod>(*ret); else throw UsageError("Unknown file ingestion method '%s', expect `flat`, `nar`, or `git`"); } } std::string_view renderFileSerialisationMethod(FileSerialisationMethod method) { switch (method) { case FileSerialisationMethod::Flat: return "flat"; case FileSerialisationMethod::NixArchive: return "nar"; default: assert(false); } } std::string_view renderFileIngestionMethod(FileIngestionMethod method) { switch (method) { case FileIngestionMethod::Flat: case FileIngestionMethod::NixArchive: return renderFileSerialisationMethod( static_cast<FileSerialisationMethod>(method)); case FileIngestionMethod::Git: return "git"; default: unreachable(); } } void dumpPath( const SourcePath & path, Sink & sink, FileSerialisationMethod method, PathFilter & filter) { switch (method) { case FileSerialisationMethod::Flat: path.readFile(sink); break; case FileSerialisationMethod::NixArchive: path.dumpPath(sink, filter); break; } } void restorePath( const Path & path, Source & source, FileSerialisationMethod method, bool startFsync) { switch (method) { case FileSerialisationMethod::Flat: writeFile(path, source, 0666, startFsync); break; case FileSerialisationMethod::NixArchive: restorePath(path, source, startFsync); break; } } HashResult hashPath( const SourcePath & path, FileSerialisationMethod method, HashAlgorithm ha, PathFilter & filter) { HashSink sink { ha }; dumpPath(path, sink, method, filter); return sink.finish(); } std::pair<Hash, std::optional<uint64_t>> hashPath( const SourcePath & path, FileIngestionMethod method, HashAlgorithm ht, PathFilter & filter) { switch (method) { case FileIngestionMethod::Flat: case FileIngestionMethod::NixArchive: { auto res = hashPath(path, (FileSerialisationMethod) method, ht, filter); return {res.first, {res.second}}; } case FileIngestionMethod::Git: return {git::dumpHash(ht, path, filter).hash, std::nullopt}; } assert(false); } }
3,230
C++
.cc
115
22.965217
101
0.688408
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,901
cgroup.cc
NixOS_nix/src/libutil/linux/cgroup.cc
#include "cgroup.hh" #include "signals.hh" #include "util.hh" #include "file-system.hh" #include "finally.hh" #include <chrono> #include <cmath> #include <regex> #include <unordered_set> #include <thread> #include <dirent.h> #include <mntent.h> namespace nix { std::optional<Path> getCgroupFS() { static auto res = [&]() -> std::optional<Path> { auto fp = fopen("/proc/mounts", "r"); if (!fp) return std::nullopt; Finally delFP = [&]() { fclose(fp); }; while (auto ent = getmntent(fp)) if (std::string_view(ent->mnt_type) == "cgroup2") return ent->mnt_dir; return std::nullopt; }(); return res; } // FIXME: obsolete, check for cgroup2 std::map<std::string, std::string> getCgroups(const Path & cgroupFile) { std::map<std::string, std::string> cgroups; for (auto & line : tokenizeString<std::vector<std::string>>(readFile(cgroupFile), "\n")) { static std::regex regex("([0-9]+):([^:]*):(.*)"); std::smatch match; if (!std::regex_match(line, match, regex)) throw Error("invalid line '%s' in '%s'", line, cgroupFile); std::string name = hasPrefix(std::string(match[2]), "name=") ? std::string(match[2], 5) : match[2]; cgroups.insert_or_assign(name, match[3]); } return cgroups; } static CgroupStats destroyCgroup(const std::filesystem::path & cgroup, bool returnStats) { if (!pathExists(cgroup)) return {}; auto procsFile = cgroup / "cgroup.procs"; if (!pathExists(procsFile)) throw Error("'%s' is not a cgroup", cgroup); /* Use the fast way to kill every process in a cgroup, if available. */ auto killFile = cgroup / "cgroup.kill"; if (pathExists(killFile)) writeFile(killFile, "1"); /* Otherwise, manually kill every process in the subcgroups and this cgroup. */ for (auto & entry : std::filesystem::directory_iterator{cgroup}) { checkInterrupt(); if (entry.symlink_status().type() != std::filesystem::file_type::directory) continue; destroyCgroup(cgroup / entry.path().filename(), false); } int round = 1; std::unordered_set<pid_t> pidsShown; while (true) { auto pids = tokenizeString<std::vector<std::string>>(readFile(procsFile)); if (pids.empty()) break; if (round > 20) throw Error("cannot kill cgroup '%s'", cgroup); for (auto & pid_s : pids) { pid_t pid; if (auto o = string2Int<pid_t>(pid_s)) pid = *o; else throw Error("invalid pid '%s'", pid); if (pidsShown.insert(pid).second) { try { auto cmdline = readFile(fmt("/proc/%d/cmdline", pid)); using namespace std::string_literals; warn("killing stray builder process %d (%s)...", pid, trim(replaceStrings(cmdline, "\0"s, " "))); } catch (SystemError &) { } } // FIXME: pid wraparound if (kill(pid, SIGKILL) == -1 && errno != ESRCH) throw SysError("killing member %d of cgroup '%s'", pid, cgroup); } auto sleep = std::chrono::milliseconds((int) std::pow(2.0, std::min(round, 10))); if (sleep.count() > 100) printError("waiting for %d ms for cgroup '%s' to become empty", sleep.count(), cgroup); std::this_thread::sleep_for(sleep); round++; } CgroupStats stats; if (returnStats) { auto cpustatPath = cgroup / "cpu.stat"; if (pathExists(cpustatPath)) { for (auto & line : tokenizeString<std::vector<std::string>>(readFile(cpustatPath), "\n")) { std::string_view userPrefix = "user_usec "; if (hasPrefix(line, userPrefix)) { auto n = string2Int<uint64_t>(line.substr(userPrefix.size())); if (n) stats.cpuUser = std::chrono::microseconds(*n); } std::string_view systemPrefix = "system_usec "; if (hasPrefix(line, systemPrefix)) { auto n = string2Int<uint64_t>(line.substr(systemPrefix.size())); if (n) stats.cpuSystem = std::chrono::microseconds(*n); } } } } if (rmdir(cgroup.c_str()) == -1) throw SysError("deleting cgroup '%s'", cgroup); return stats; } CgroupStats destroyCgroup(const Path & cgroup) { return destroyCgroup(cgroup, true); } std::string getCurrentCgroup() { auto cgroupFS = getCgroupFS(); if (!cgroupFS) throw Error("cannot determine the cgroups file system"); auto ourCgroups = getCgroups("/proc/self/cgroup"); auto ourCgroup = ourCgroups[""]; if (ourCgroup == "") throw Error("cannot determine cgroup name from /proc/self/cgroup"); return ourCgroup; } std::string getRootCgroup() { static std::string rootCgroup = getCurrentCgroup(); return rootCgroup; } }
5,081
C++
.cc
133
30.052632
107
0.580671
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,902
namespaces.cc
NixOS_nix/src/libutil/linux/namespaces.cc
#include "current-process.hh" #include "util.hh" #include "finally.hh" #include "file-system.hh" #include "processes.hh" #include "signals.hh" #include <mutex> #include <sys/resource.h> #include "cgroup.hh" #include <sys/mount.h> namespace nix { bool userNamespacesSupported() { static auto res = [&]() -> bool { if (!pathExists("/proc/self/ns/user")) { debug("'/proc/self/ns/user' does not exist; your kernel was likely built without CONFIG_USER_NS=y"); return false; } Path maxUserNamespaces = "/proc/sys/user/max_user_namespaces"; if (!pathExists(maxUserNamespaces) || trim(readFile(maxUserNamespaces)) == "0") { debug("user namespaces appear to be disabled; check '/proc/sys/user/max_user_namespaces'"); return false; } Path procSysKernelUnprivilegedUsernsClone = "/proc/sys/kernel/unprivileged_userns_clone"; if (pathExists(procSysKernelUnprivilegedUsernsClone) && trim(readFile(procSysKernelUnprivilegedUsernsClone)) == "0") { debug("user namespaces appear to be disabled; check '/proc/sys/kernel/unprivileged_userns_clone'"); return false; } try { Pid pid = startProcess([&]() { _exit(0); }, { .cloneFlags = CLONE_NEWUSER }); auto r = pid.wait(); assert(!r); } catch (SysError & e) { debug("user namespaces do not work on this system: %s", e.msg()); return false; } return true; }(); return res; } bool mountAndPidNamespacesSupported() { static auto res = [&]() -> bool { try { Pid pid = startProcess([&]() { /* Make sure we don't remount the parent's /proc. */ if (mount(0, "/", 0, MS_PRIVATE | MS_REC, 0) == -1) _exit(1); /* Test whether we can remount /proc. The kernel disallows this if /proc is not fully visible, i.e. if there are filesystems mounted on top of files inside /proc. See https://lore.kernel.org/lkml/87tvsrjai0.fsf@xmission.com/T/. */ if (mount("none", "/proc", "proc", 0, 0) == -1) _exit(2); _exit(0); }, { .cloneFlags = CLONE_NEWNS | CLONE_NEWPID | (userNamespacesSupported() ? CLONE_NEWUSER : 0) }); if (pid.wait()) { debug("PID namespaces do not work on this system: cannot remount /proc"); return false; } } catch (SysError & e) { debug("mount namespaces do not work on this system: %s", e.msg()); return false; } return true; }(); return res; } ////////////////////////////////////////////////////////////////////// static AutoCloseFD fdSavedMountNamespace; static AutoCloseFD fdSavedRoot; void saveMountNamespace() { static std::once_flag done; std::call_once(done, []() { fdSavedMountNamespace = open("/proc/self/ns/mnt", O_RDONLY); if (!fdSavedMountNamespace) throw SysError("saving parent mount namespace"); fdSavedRoot = open("/proc/self/root", O_RDONLY); }); } void restoreMountNamespace() { try { auto savedCwd = std::filesystem::current_path(); if (fdSavedMountNamespace && setns(fdSavedMountNamespace.get(), CLONE_NEWNS) == -1) throw SysError("restoring parent mount namespace"); if (fdSavedRoot) { if (fchdir(fdSavedRoot.get())) throw SysError("chdir into saved root"); if (chroot(".")) throw SysError("chroot into saved root"); } if (chdir(savedCwd.c_str()) == -1) throw SysError("restoring cwd"); } catch (Error & e) { debug(e.msg()); } } void tryUnshareFilesystem() { if (unshare(CLONE_FS) != 0 && errno != EPERM && errno != ENOSYS) throw SysError("unsharing filesystem state"); } }
4,178
C++
.cc
119
26.142857
112
0.551091
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,903
local-keys.cc
NixOS_nix/src/libutil/signature/local-keys.cc
#include "signature/local-keys.hh" #include "file-system.hh" #include "util.hh" #include <sodium.h> namespace nix { BorrowedCryptoValue BorrowedCryptoValue::parse(std::string_view s) { size_t colon = s.find(':'); if (colon == std::string::npos || colon == 0) return {"", ""}; return {s.substr(0, colon), s.substr(colon + 1)}; } Key::Key(std::string_view s, bool sensitiveValue) { auto ss = BorrowedCryptoValue::parse(s); name = ss.name; key = ss.payload; try { if (name == "" || key == "") throw FormatError("key is corrupt"); key = base64Decode(key); } catch (Error & e) { std::string extra; if (!sensitiveValue) extra = fmt(" with raw value '%s'", key); e.addTrace({}, "while decoding key named '%s'%s", name, extra); throw; } } std::string Key::to_string() const { return name + ":" + base64Encode(key); } SecretKey::SecretKey(std::string_view s) : Key{s, true} { if (key.size() != crypto_sign_SECRETKEYBYTES) throw Error("secret key is not valid"); } std::string SecretKey::signDetached(std::string_view data) const { unsigned char sig[crypto_sign_BYTES]; unsigned long long sigLen; crypto_sign_detached(sig, &sigLen, (unsigned char *) data.data(), data.size(), (unsigned char *) key.data()); return name + ":" + base64Encode(std::string((char *) sig, sigLen)); } PublicKey SecretKey::toPublicKey() const { unsigned char pk[crypto_sign_PUBLICKEYBYTES]; crypto_sign_ed25519_sk_to_pk(pk, (unsigned char *) key.data()); return PublicKey(name, std::string((char *) pk, crypto_sign_PUBLICKEYBYTES)); } SecretKey SecretKey::generate(std::string_view name) { unsigned char pk[crypto_sign_PUBLICKEYBYTES]; unsigned char sk[crypto_sign_SECRETKEYBYTES]; if (crypto_sign_keypair(pk, sk) != 0) throw Error("key generation failed"); return SecretKey(name, std::string((char *) sk, crypto_sign_SECRETKEYBYTES)); } PublicKey::PublicKey(std::string_view s) : Key{s, false} { if (key.size() != crypto_sign_PUBLICKEYBYTES) throw Error("public key is not valid"); } bool PublicKey::verifyDetached(std::string_view data, std::string_view sig) const { auto ss = BorrowedCryptoValue::parse(sig); if (ss.name != std::string_view { name }) return false; return verifyDetachedAnon(data, ss.payload); } bool PublicKey::verifyDetachedAnon(std::string_view data, std::string_view sig) const { std::string sig2; try { sig2 = base64Decode(sig); } catch (Error & e) { e.addTrace({}, "while decoding signature '%s'", sig); } if (sig2.size() != crypto_sign_BYTES) throw Error("signature is not valid"); return crypto_sign_verify_detached((unsigned char *) sig2.data(), (unsigned char *) data.data(), data.size(), (unsigned char *) key.data()) == 0; } bool verifyDetached(std::string_view data, std::string_view sig, const PublicKeys & publicKeys) { auto ss = BorrowedCryptoValue::parse(sig); auto key = publicKeys.find(std::string(ss.name)); if (key == publicKeys.end()) return false; return key->second.verifyDetachedAnon(data, ss.payload); } }
3,244
C++
.cc
95
29.705263
95
0.65739
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,904
signer.cc
NixOS_nix/src/libutil/signature/signer.cc
#include "signature/signer.hh" #include "error.hh" #include <sodium.h> namespace nix { LocalSigner::LocalSigner(SecretKey && privateKey) : privateKey(privateKey) , publicKey(privateKey.toPublicKey()) { } std::string LocalSigner::signDetached(std::string_view s) const { return privateKey.signDetached(s); } const PublicKey & LocalSigner::getPublicKey() { return publicKey; } }
399
C++
.cc
17
21.176471
63
0.763298
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,905
processes.cc
NixOS_nix/src/libutil/unix/processes.cc
#include "current-process.hh" #include "environment-variables.hh" #include "executable-path.hh" #include "signals.hh" #include "processes.hh" #include "finally.hh" #include "serialise.hh" #include <cerrno> #include <cstdlib> #include <cstring> #include <future> #include <iostream> #include <sstream> #include <thread> #include <grp.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #ifdef __APPLE__ # include <sys/syscall.h> #endif #ifdef __linux__ # include <sys/prctl.h> # include <sys/mman.h> #endif namespace nix { Pid::Pid() { } Pid::Pid(pid_t pid) : pid(pid) { } Pid::~Pid() { if (pid != -1) kill(); } void Pid::operator =(pid_t pid) { if (this->pid != -1 && this->pid != pid) kill(); this->pid = pid; killSignal = SIGKILL; // reset signal to default } Pid::operator pid_t() { return pid; } int Pid::kill() { assert(pid != -1); debug("killing process %1%", pid); /* Send the requested signal to the child. If it has its own process group, send the signal to every process in the child process group (which hopefully includes *all* its children). */ if (::kill(separatePG ? -pid : pid, killSignal) != 0) { /* On BSDs, killing a process group will return EPERM if all processes in the group are zombies (or something like that). So try to detect and ignore that situation. */ #if __FreeBSD__ || __APPLE__ if (errno != EPERM || ::kill(pid, 0) != 0) #endif logError(SysError("killing process %d", pid).info()); } return wait(); } int Pid::wait() { assert(pid != -1); while (1) { int status; int res = waitpid(pid, &status, 0); if (res == pid) { pid = -1; return status; } if (errno != EINTR) throw SysError("cannot get exit status of PID %d", pid); checkInterrupt(); } } void Pid::setSeparatePG(bool separatePG) { this->separatePG = separatePG; } void Pid::setKillSignal(int signal) { this->killSignal = signal; } pid_t Pid::release() { pid_t p = pid; pid = -1; return p; } void killUser(uid_t uid) { debug("killing all processes running under uid '%1%'", uid); assert(uid != 0); /* just to be safe... */ /* The system call kill(-1, sig) sends the signal `sig' to all users to which the current process can send signals. So we fork a process, switch to uid, and send a mass kill. */ Pid pid = startProcess([&] { if (setuid(uid) == -1) throw SysError("setting uid"); while (true) { #ifdef __APPLE__ /* OSX's kill syscall takes a third parameter that, among other things, determines if kill(-1, signo) affects the calling process. In the OSX libc, it's set to true, which means "follow POSIX", which we don't want here */ if (syscall(SYS_kill, -1, SIGKILL, false) == 0) break; #else if (kill(-1, SIGKILL) == 0) break; #endif if (errno == ESRCH || errno == EPERM) break; /* no more processes */ if (errno != EINTR) throw SysError("cannot kill processes for uid '%1%'", uid); } _exit(0); }); int status = pid.wait(); if (status != 0) throw Error("cannot kill processes for uid '%1%': %2%", uid, statusToString(status)); /* !!! We should really do some check to make sure that there are no processes left running under `uid', but there is no portable way to do so (I think). The most reliable way may be `ps -eo uid | grep -q $uid'. */ } ////////////////////////////////////////////////////////////////////// using ChildWrapperFunction = std::function<void()>; /* Wrapper around vfork to prevent the child process from clobbering the caller's stack frame in the parent. */ static pid_t doFork(bool allowVfork, ChildWrapperFunction & fun) __attribute__((noinline)); static pid_t doFork(bool allowVfork, ChildWrapperFunction & fun) { #ifdef __linux__ pid_t pid = allowVfork ? vfork() : fork(); #else pid_t pid = fork(); #endif if (pid != 0) return pid; fun(); unreachable(); } #if __linux__ static int childEntry(void * arg) { auto & fun = *reinterpret_cast<ChildWrapperFunction*>(arg); fun(); return 1; } #endif pid_t startProcess(std::function<void()> fun, const ProcessOptions & options) { ChildWrapperFunction wrapper = [&] { if (!options.allowVfork) logger = makeSimpleLogger(); try { #if __linux__ if (options.dieWithParent && prctl(PR_SET_PDEATHSIG, SIGKILL) == -1) throw SysError("setting death signal"); #endif fun(); } catch (std::exception & e) { try { std::cerr << options.errorPrefix << e.what() << "\n"; } catch (...) { } } catch (...) { } if (options.runExitHandlers) exit(1); else _exit(1); }; pid_t pid = -1; if (options.cloneFlags) { #ifdef __linux__ // Not supported, since then we don't know when to free the stack. assert(!(options.cloneFlags & CLONE_VM)); size_t stackSize = 1 * 1024 * 1024; auto stack = static_cast<char *>(mmap(0, stackSize, PROT_WRITE | PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0)); if (stack == MAP_FAILED) throw SysError("allocating stack"); Finally freeStack([&] { munmap(stack, stackSize); }); pid = clone(childEntry, stack + stackSize, options.cloneFlags | SIGCHLD, &wrapper); #else throw Error("clone flags are only supported on Linux"); #endif } else pid = doFork(options.allowVfork, wrapper); if (pid == -1) throw SysError("unable to fork"); return pid; } std::string runProgram(Path program, bool lookupPath, const Strings & args, const std::optional<std::string> & input, bool isInteractive) { auto res = runProgram(RunOptions {.program = program, .lookupPath = lookupPath, .args = args, .input = input, .isInteractive = isInteractive}); if (!statusOk(res.first)) throw ExecError(res.first, "program '%1%' %2%", program, statusToString(res.first)); return res.second; } // Output = error code + "standard out" output stream std::pair<int, std::string> runProgram(RunOptions && options) { StringSink sink; options.standardOut = &sink; int status = 0; try { runProgram2(options); } catch (ExecError & e) { status = e.status; } return {status, std::move(sink.s)}; } void runProgram2(const RunOptions & options) { checkInterrupt(); assert(!(options.standardIn && options.input)); std::unique_ptr<Source> source_; Source * source = options.standardIn; if (options.input) { source_ = std::make_unique<StringSource>(*options.input); source = source_.get(); } /* Create a pipe. */ Pipe out, in; if (options.standardOut) out.create(); if (source) in.create(); ProcessOptions processOptions; // vfork implies that the environment of the main process and the fork will // be shared (technically this is undefined, but in practice that's the // case), so we can't use it if we alter the environment processOptions.allowVfork = !options.environment; std::optional<Finally<std::function<void()>>> resumeLoggerDefer; if (options.isInteractive) { logger->pause(); resumeLoggerDefer.emplace( []() { logger->resume(); } ); } /* Fork. */ Pid pid = startProcess([&] { if (options.environment) replaceEnv(*options.environment); if (options.standardOut && dup2(out.writeSide.get(), STDOUT_FILENO) == -1) throw SysError("dupping stdout"); if (options.mergeStderrToStdout) if (dup2(STDOUT_FILENO, STDERR_FILENO) == -1) throw SysError("cannot dup stdout into stderr"); if (source && dup2(in.readSide.get(), STDIN_FILENO) == -1) throw SysError("dupping stdin"); if (options.chdir && chdir((*options.chdir).c_str()) == -1) throw SysError("chdir failed"); if (options.gid && setgid(*options.gid) == -1) throw SysError("setgid failed"); /* Drop all other groups if we're setgid. */ if (options.gid && setgroups(0, 0) == -1) throw SysError("setgroups failed"); if (options.uid && setuid(*options.uid) == -1) throw SysError("setuid failed"); Strings args_(options.args); args_.push_front(options.program); restoreProcessContext(); if (options.lookupPath) execvp(options.program.c_str(), stringsToCharPtrs(args_).data()); // This allows you to refer to a program with a pathname relative // to the PATH variable. else execv(options.program.c_str(), stringsToCharPtrs(args_).data()); throw SysError("executing '%1%'", options.program); }, processOptions); out.writeSide.close(); std::thread writerThread; std::promise<void> promise; Finally doJoin([&] { if (writerThread.joinable()) writerThread.join(); }); if (source) { in.readSide.close(); writerThread = std::thread([&] { try { std::vector<char> buf(8 * 1024); while (true) { size_t n; try { n = source->read(buf.data(), buf.size()); } catch (EndOfFile &) { break; } writeFull(in.writeSide.get(), {buf.data(), n}); } promise.set_value(); } catch (...) { promise.set_exception(std::current_exception()); } in.writeSide.close(); }); } if (options.standardOut) drainFD(out.readSide.get(), *options.standardOut); /* Wait for the child to finish. */ int status = pid.wait(); /* Wait for the writer thread to finish. */ if (source) promise.get_future().get(); if (status) throw ExecError(status, "program '%1%' %2%", options.program, statusToString(status)); } ////////////////////////////////////////////////////////////////////// std::string statusToString(int status) { if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { if (WIFEXITED(status)) return fmt("failed with exit code %1%", WEXITSTATUS(status)); else if (WIFSIGNALED(status)) { int sig = WTERMSIG(status); #if HAVE_STRSIGNAL const char * description = strsignal(sig); return fmt("failed due to signal %1% (%2%)", sig, description); #else return fmt("failed due to signal %1%", sig); #endif } else return "died abnormally"; } else return "succeeded"; } bool statusOk(int status) { return WIFEXITED(status) && WEXITSTATUS(status) == 0; } int execvpe(const char * file0, const char * const argv[], const char * const envp[]) { auto file = ExecutablePath::load().findPath(file0); // `const_cast` is safe. See the note in // https://pubs.opengroup.org/onlinepubs/9799919799/functions/exec.html return execve(file.c_str(), const_cast<char *const *>(argv), const_cast<char *const *>(envp)); } }
11,595
C++
.cc
341
27.307918
147
0.589842
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,906
muxable-pipe.cc
NixOS_nix/src/libutil/unix/muxable-pipe.cc
#include <poll.h> #include "logging.hh" #include "util.hh" #include "muxable-pipe.hh" namespace nix { void MuxablePipePollState::poll(std::optional<unsigned int> timeout) { if (::poll(pollStatus.data(), pollStatus.size(), timeout ? *timeout : -1) == -1) { if (errno == EINTR) return; throw SysError("waiting for input"); } } void MuxablePipePollState::iterate( std::set<MuxablePipePollState::CommChannel> & channels, std::function<void(Descriptor fd, std::string_view data)> handleRead, std::function<void(Descriptor fd)> handleEOF) { std::set<Descriptor> fds2(channels); std::vector<unsigned char> buffer(4096); for (auto & k : fds2) { const auto fdPollStatusId = get(fdToPollStatus, k); assert(fdPollStatusId); assert(*fdPollStatusId < pollStatus.size()); if (pollStatus.at(*fdPollStatusId).revents) { ssize_t rd = ::read(fromDescriptorReadOnly(k), buffer.data(), buffer.size()); // FIXME: is there a cleaner way to handle pt close // than EIO? Is this even standard? if (rd == 0 || (rd == -1 && errno == EIO)) { handleEOF(k); channels.erase(k); } else if (rd == -1) { if (errno != EINTR) throw SysError("read failed"); } else { std::string_view data((char *) buffer.data(), rd); handleRead(k, data); } } } } }
1,506
C++
.cc
42
27.880952
89
0.580535
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,907
file-descriptor.cc
NixOS_nix/src/libutil/unix/file-descriptor.cc
#include "file-system.hh" #include "signals.hh" #include "finally.hh" #include "serialise.hh" #include <fcntl.h> #include <unistd.h> namespace nix { std::string readFile(int fd) { struct stat st; if (fstat(fd, &st) == -1) throw SysError("statting file"); return drainFD(fd, true, st.st_size); } void readFull(int fd, char * buf, size_t count) { while (count) { checkInterrupt(); ssize_t res = read(fd, buf, count); if (res == -1) { if (errno == EINTR) continue; throw SysError("reading from file"); } if (res == 0) throw EndOfFile("unexpected end-of-file"); count -= res; buf += res; } } void writeFull(int fd, std::string_view s, bool allowInterrupts) { while (!s.empty()) { if (allowInterrupts) checkInterrupt(); ssize_t res = write(fd, s.data(), s.size()); if (res == -1 && errno != EINTR) throw SysError("writing to file"); if (res > 0) s.remove_prefix(res); } } std::string readLine(int fd, bool eofOk) { std::string s; while (1) { checkInterrupt(); char ch; // FIXME: inefficient ssize_t rd = read(fd, &ch, 1); if (rd == -1) { if (errno != EINTR) throw SysError("reading a line"); } else if (rd == 0) { if (eofOk) return s; else throw EndOfFile("unexpected EOF reading a line"); } else { if (ch == '\n') return s; s += ch; } } } void drainFD(int fd, Sink & sink, bool block) { // silence GCC maybe-uninitialized warning in finally int saved = 0; if (!block) { saved = fcntl(fd, F_GETFL); if (fcntl(fd, F_SETFL, saved | O_NONBLOCK) == -1) throw SysError("making file descriptor non-blocking"); } Finally finally([&]() { if (!block) { if (fcntl(fd, F_SETFL, saved) == -1) throw SysError("making file descriptor blocking"); } }); std::vector<unsigned char> buf(64 * 1024); while (1) { checkInterrupt(); ssize_t rd = read(fd, buf.data(), buf.size()); if (rd == -1) { if (!block && (errno == EAGAIN || errno == EWOULDBLOCK)) break; if (errno != EINTR) throw SysError("reading from file"); } else if (rd == 0) break; else sink({reinterpret_cast<char *>(buf.data()), (size_t) rd}); } } ////////////////////////////////////////////////////////////////////// void Pipe::create() { int fds[2]; #if HAVE_PIPE2 if (pipe2(fds, O_CLOEXEC) != 0) throw SysError("creating pipe"); #else if (pipe(fds) != 0) throw SysError("creating pipe"); unix::closeOnExec(fds[0]); unix::closeOnExec(fds[1]); #endif readSide = fds[0]; writeSide = fds[1]; } ////////////////////////////////////////////////////////////////////// #if __linux__ || __FreeBSD__ static int unix_close_range(unsigned int first, unsigned int last, int flags) { #if !HAVE_CLOSE_RANGE return syscall(SYS_close_range, first, last, (unsigned int)flags); #else return close_range(first, last, flags); #endif } #endif void unix::closeExtraFDs() { constexpr int MAX_KEPT_FD = 2; static_assert(std::max({STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO}) == MAX_KEPT_FD); #if __linux__ || __FreeBSD__ // first try to close_range everything we don't care about. if this // returns an error with these parameters we're running on a kernel // that does not implement close_range (i.e. pre 5.9) and fall back // to the old method. we should remove that though, in some future. if (unix_close_range(MAX_KEPT_FD + 1, ~0U, 0) == 0) { return; } #endif #if __linux__ try { for (auto & s : std::filesystem::directory_iterator{"/proc/self/fd"}) { checkInterrupt(); auto fd = std::stoi(s.path().filename()); if (fd > MAX_KEPT_FD) { debug("closing leaked FD %d", fd); close(fd); } } return; } catch (SysError &) { } catch (std::filesystem::filesystem_error &) { } #endif int maxFD = 0; #if HAVE_SYSCONF maxFD = sysconf(_SC_OPEN_MAX); #endif for (int fd = MAX_KEPT_FD + 1; fd < maxFD; ++fd) close(fd); /* ignore result */ } void unix::closeOnExec(int fd) { int prev; if ((prev = fcntl(fd, F_GETFD, 0)) == -1 || fcntl(fd, F_SETFD, prev | FD_CLOEXEC) == -1) throw SysError("setting close-on-exec flag"); } }
4,671
C++
.cc
159
23.075472
89
0.541137
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,908
signals.cc
NixOS_nix/src/libutil/unix/signals.cc
#include "signals.hh" #include "util.hh" #include "error.hh" #include "sync.hh" #include "terminal.hh" #include <thread> namespace nix { using namespace unix; std::atomic<bool> unix::_isInterrupted = false; namespace unix { static thread_local bool interruptThrown = false; } thread_local std::function<bool()> unix::interruptCheck; void setInterruptThrown() { unix::interruptThrown = true; } void unix::_interrupted() { /* Block user interrupts while an exception is being handled. Throwing an exception while another exception is being handled kills the program! */ if (!interruptThrown && !std::uncaught_exceptions()) { interruptThrown = true; throw Interrupted("interrupted by the user"); } } ////////////////////////////////////////////////////////////////////// /* We keep track of interrupt callbacks using integer tokens, so we can iterate safely without having to lock the data structure while executing arbitrary functions. */ struct InterruptCallbacks { typedef int64_t Token; /* We use unique tokens so that we can't accidentally delete the wrong handler because of an erroneous double delete. */ Token nextToken = 0; /* Used as a list, see InterruptCallbacks comment. */ std::map<Token, std::function<void()>> callbacks; }; static Sync<InterruptCallbacks> _interruptCallbacks; static void signalHandlerThread(sigset_t set) { while (true) { int signal = 0; sigwait(&set, &signal); if (signal == SIGINT || signal == SIGTERM || signal == SIGHUP) triggerInterrupt(); else if (signal == SIGWINCH) { updateWindowSize(); } } } void unix::triggerInterrupt() { _isInterrupted = true; { InterruptCallbacks::Token i = 0; while (true) { std::function<void()> callback; { auto interruptCallbacks(_interruptCallbacks.lock()); auto lb = interruptCallbacks->callbacks.lower_bound(i); if (lb == interruptCallbacks->callbacks.end()) break; callback = lb->second; i = lb->first + 1; } try { callback(); } catch (...) { ignoreExceptionInDestructor(); } } } } static sigset_t savedSignalMask; static bool savedSignalMaskIsSet = false; void unix::setChildSignalMask(sigset_t * sigs) { assert(sigs); // C style function, but think of sigs as a reference #if _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE sigemptyset(&savedSignalMask); // There's no "assign" or "copy" function, so we rely on (math) idempotence // of the or operator: a or a = a. sigorset(&savedSignalMask, sigs, sigs); #else // Without sigorset, our best bet is to assume that sigset_t is a type that // can be assigned directly, such as is the case for a sigset_t defined as // an integer type. savedSignalMask = *sigs; #endif savedSignalMaskIsSet = true; } void unix::saveSignalMask() { if (sigprocmask(SIG_BLOCK, nullptr, &savedSignalMask)) throw SysError("querying signal mask"); savedSignalMaskIsSet = true; } void unix::startSignalHandlerThread() { updateWindowSize(); saveSignalMask(); sigset_t set; sigemptyset(&set); sigaddset(&set, SIGINT); sigaddset(&set, SIGTERM); sigaddset(&set, SIGHUP); sigaddset(&set, SIGPIPE); sigaddset(&set, SIGWINCH); if (pthread_sigmask(SIG_BLOCK, &set, nullptr)) throw SysError("blocking signals"); std::thread(signalHandlerThread, set).detach(); } void unix::restoreSignals() { // If startSignalHandlerThread wasn't called, that means we're not running // in a proper libmain process, but a process that presumably manages its // own signal handlers. Such a process should call either // - initNix(), to be a proper libmain process // - startSignalHandlerThread(), to resemble libmain regarding signal // handling only // - saveSignalMask(), for processes that define their own signal handling // thread // TODO: Warn about this? Have a default signal mask? The latter depends on // whether we should generally inherit signal masks from the caller. // I don't know what the larger unix ecosystem expects from us here. if (!savedSignalMaskIsSet) return; if (sigprocmask(SIG_SETMASK, &savedSignalMask, nullptr)) throw SysError("restoring signals"); } /* RAII helper to automatically deregister a callback. */ struct InterruptCallbackImpl : InterruptCallback { InterruptCallbacks::Token token; ~InterruptCallbackImpl() override { auto interruptCallbacks(_interruptCallbacks.lock()); interruptCallbacks->callbacks.erase(token); } }; std::unique_ptr<InterruptCallback> createInterruptCallback(std::function<void()> callback) { auto interruptCallbacks(_interruptCallbacks.lock()); auto token = interruptCallbacks->nextToken++; interruptCallbacks->callbacks.emplace(token, callback); std::unique_ptr<InterruptCallbackImpl> res {new InterruptCallbackImpl{}}; res->token = token; return std::unique_ptr<InterruptCallback>(res.release()); } }
5,325
C++
.cc
152
29.657895
90
0.671083
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,909
os-string.cc
NixOS_nix/src/libutil/unix/os-string.cc
#include <algorithm> #include <codecvt> #include <iostream> #include <locale> #include "file-path.hh" #include "util.hh" namespace nix { std::string os_string_to_string(PathViewNG::string_view path) { return std::string{path}; } std::filesystem::path::string_type string_to_os_string(std::string_view s) { return std::string{s}; } }
346
C++
.cc
16
19.8125
74
0.741538
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,910
users.cc
NixOS_nix/src/libutil/unix/users.cc
#include "util.hh" #include "users.hh" #include "environment-variables.hh" #include "file-system.hh" #include <pwd.h> #include <sys/types.h> #include <unistd.h> namespace nix { namespace fs { using namespace std::filesystem; } std::string getUserName() { auto pw = getpwuid(geteuid()); std::string name = pw ? pw->pw_name : getEnv("USER").value_or(""); if (name.empty()) throw Error("cannot figure out user name"); return name; } Path getHomeOf(uid_t userId) { std::vector<char> buf(16384); struct passwd pwbuf; struct passwd * pw; if (getpwuid_r(userId, &pwbuf, buf.data(), buf.size(), &pw) != 0 || !pw || !pw->pw_dir || !pw->pw_dir[0]) throw Error("cannot determine user's home directory"); return pw->pw_dir; } Path getHome() { static Path homeDir = []() { std::optional<std::string> unownedUserHomeDir = {}; auto homeDir = getEnv("HOME"); if (homeDir) { // Only use $HOME if doesn't exist or is owned by the current user. struct stat st; int result = stat(homeDir->c_str(), &st); if (result != 0) { if (errno != ENOENT) { warn("couldn't stat $HOME ('%s') for reason other than not existing ('%d'), falling back to the one defined in the 'passwd' file", *homeDir, errno); homeDir.reset(); } } else if (st.st_uid != geteuid()) { unownedUserHomeDir.swap(homeDir); } } if (!homeDir) { homeDir = getHomeOf(geteuid()); if (unownedUserHomeDir.has_value() && unownedUserHomeDir != homeDir) { warn("$HOME ('%s') is not owned by you, falling back to the one defined in the 'passwd' file ('%s')", *unownedUserHomeDir, *homeDir); } } return *homeDir; }(); return homeDir; } bool isRootUser() { return getuid() == 0; } }
1,968
C++
.cc
60
25.866667
168
0.571579
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,911
file-path.cc
NixOS_nix/src/libutil/unix/file-path.cc
#include <algorithm> #include <codecvt> #include <iostream> #include <locale> #include "file-path.hh" #include "util.hh" namespace nix { std::optional<std::filesystem::path> maybePath(PathView path) { return { path }; } std::filesystem::path pathNG(PathView path) { return path; } }
296
C++
.cc
16
16.6875
61
0.741818
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,912
environment-variables.cc
NixOS_nix/src/libutil/unix/environment-variables.cc
#include <cstdlib> #include "environment-variables.hh" namespace nix { int setEnv(const char * name, const char * value) { return ::setenv(name, value, 1); } std::optional<std::string> getEnvOs(const std::string & key) { return getEnv(key); } int setEnvOs(const OsString & name, const OsString & value) { return setEnv(name.c_str(), value.c_str()); } }
371
C++
.cc
16
21.0625
60
0.710602
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,913
file-system.cc
NixOS_nix/src/libutil/unix/file-system.cc
#include "file-system.hh" namespace nix { Descriptor openDirectory(const std::filesystem::path & path) { return open(path.c_str(), O_RDONLY | O_DIRECTORY); } }
167
C++
.cc
7
21.857143
60
0.732484
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,914
windows-async-pipe.cc
NixOS_nix/src/libutil/windows/windows-async-pipe.cc
#include "windows-async-pipe.hh" #include "windows-error.hh" namespace nix::windows { void AsyncPipe::createAsyncPipe(HANDLE iocp) { // std::cerr << (format("-----AsyncPipe::createAsyncPipe(%x)") % iocp) << std::endl; buffer.resize(0x1000); memset(&overlapped, 0, sizeof(overlapped)); std::string pipeName = fmt("\\\\.\\pipe\\nix-%d-%p", GetCurrentProcessId(), (void *) this); readSide = CreateNamedPipeA( pipeName.c_str(), PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE, PIPE_UNLIMITED_INSTANCES, 0, 0, INFINITE, NULL); if (!readSide) throw WinError("CreateNamedPipeA(%s)", pipeName); HANDLE hIocp = CreateIoCompletionPort(readSide.get(), iocp, (ULONG_PTR) (readSide.get()) ^ 0x5555, 0); if (hIocp != iocp) throw WinError("CreateIoCompletionPort(%x[%s], %x, ...) returned %x", readSide.get(), pipeName, iocp, hIocp); if (!ConnectNamedPipe(readSide.get(), &overlapped) && GetLastError() != ERROR_IO_PENDING) throw WinError("ConnectNamedPipe(%s)", pipeName); SECURITY_ATTRIBUTES psa2 = {0}; psa2.nLength = sizeof(SECURITY_ATTRIBUTES); psa2.bInheritHandle = TRUE; writeSide = CreateFileA(pipeName.c_str(), GENERIC_WRITE, 0, &psa2, OPEN_EXISTING, 0, NULL); if (!readSide) throw WinError("CreateFileA(%s)", pipeName); } void AsyncPipe::close() { readSide.close(); writeSide.close(); } }
1,466
C++
.cc
38
33.078947
117
0.651376
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,915
processes.cc
NixOS_nix/src/libutil/windows/processes.cc
#include "current-process.hh" #include "environment-variables.hh" #include "error.hh" #include "executable-path.hh" #include "file-descriptor.hh" #include "file-path.hh" #include "signals.hh" #include "processes.hh" #include "finally.hh" #include "serialise.hh" #include "file-system.hh" #include "util.hh" #include "windows-error.hh" #include <cerrno> #include <cstdlib> #include <cstring> #include <future> #include <iostream> #include <sstream> #include <thread> #include <sys/types.h> #include <unistd.h> #define WIN32_LEAN_AND_MEAN #include <windows.h> namespace nix { using namespace nix::windows; Pid::Pid() {} Pid::Pid(AutoCloseFD pid) : pid(std::move(pid)) { } Pid::~Pid() { if (pid.get() != INVALID_DESCRIPTOR) kill(); } void Pid::operator=(AutoCloseFD pid) { if (this->pid.get() != INVALID_DESCRIPTOR && this->pid.get() != pid.get()) kill(); this->pid = std::move(pid); } // TODO: Implement (not needed for process spawning yet) int Pid::kill() { assert(pid.get() != INVALID_DESCRIPTOR); debug("killing process %1%", pid.get()); throw UnimplementedError("Pid::kill unimplemented"); } int Pid::wait() { // https://github.com/nix-windows/nix/blob/windows-meson/src/libutil/util.cc#L1938 assert(pid.get() != INVALID_DESCRIPTOR); DWORD status = WaitForSingleObject(pid.get(), INFINITE); if (status != WAIT_OBJECT_0) { debug("WaitForSingleObject returned %1%", status); } DWORD exitCode = 0; if (GetExitCodeProcess(pid.get(), &exitCode) == FALSE) { debug("GetExitCodeProcess failed on pid %1%", pid.get()); } pid.close(); return exitCode; } // TODO: Merge this with Unix's runProgram since it's identical logic. std::string runProgram( Path program, bool lookupPath, const Strings & args, const std::optional<std::string> & input, bool isInteractive) { auto res = runProgram(RunOptions{ .program = program, .lookupPath = lookupPath, .args = args, .input = input, .isInteractive = isInteractive}); if (!statusOk(res.first)) throw ExecError(res.first, "program '%1%' %2%", program, statusToString(res.first)); return res.second; } std::optional<Path> getProgramInterpreter(const Path & program) { // These extensions are automatically handled by Windows and don't require an interpreter. static constexpr const char * exts[] = {".exe", ".cmd", ".bat"}; for (const auto ext : exts) { if (hasSuffix(program, ext)) { return {}; } } // TODO: Open file and read the shebang throw UnimplementedError("getProgramInterpreter unimplemented"); } // TODO: Not sure if this is needed in the unix version but it might be useful as a member func void setFDInheritable(AutoCloseFD & fd, bool inherit) { if (fd.get() != INVALID_DESCRIPTOR) { if (!SetHandleInformation(fd.get(), HANDLE_FLAG_INHERIT, inherit ? HANDLE_FLAG_INHERIT : 0)) { throw WinError("Couldn't disable inheriting of handle"); } } } AutoCloseFD nullFD() { // Create null handle to discard reads / writes // https://stackoverflow.com/a/25609668 // https://github.com/nix-windows/nix/blob/windows-meson/src/libutil/util.cc#L2228 AutoCloseFD nul = CreateFileW( L"NUL", GENERIC_READ | GENERIC_WRITE, // We don't care who reads / writes / deletes this file since it's NUL anyways FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, 0, NULL); if (!nul.get()) { throw WinError("Couldn't open NUL device"); } // Let this handle be inheritable by child processes setFDInheritable(nul, true); return nul; } // Adapted from // https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/ std::string windowsEscape(const std::string & str, bool cmd) { // TODO: This doesn't handle cmd.exe escaping. if (cmd) { throw UnimplementedError("cmd.exe escaping is not implemented"); } if (str.find_first_of(" \t\n\v\"") == str.npos && !str.empty()) { // No need to escape this one, the nonempty contents don't have a special character return str; } std::string buffer; // Add the opening quote buffer += '"'; for (auto iter = str.begin();; ++iter) { size_t backslashes = 0; while (iter != str.end() && *iter == '\\') { ++iter; ++backslashes; } // We only escape backslashes if: // - They come immediately before the closing quote // - They come immediately before a quote in the middle of the string // Both of these cases break the escaping if not handled. Otherwise backslashes are fine as-is if (iter == str.end()) { // Need to escape each backslash buffer.append(backslashes * 2, '\\'); // Exit since we've reached the end of the string break; } else if (*iter == '"') { // Need to escape each backslash and the intermediate quote character buffer.append(backslashes * 2, '\\'); buffer += "\\\""; } else { // Don't escape the backslashes since they won't break the delimiter buffer.append(backslashes, '\\'); buffer += *iter; } } // Add the closing quote return buffer + '"'; } Pid spawnProcess(const Path & realProgram, const RunOptions & options, Pipe & out, Pipe & in) { // Setup pipes. if (options.standardOut) { // Don't inherit the read end of the output pipe setFDInheritable(out.readSide, false); } else { out.writeSide = nullFD(); } if (options.standardIn) { // Don't inherit the write end of the input pipe setFDInheritable(in.writeSide, false); } else { in.readSide = nullFD(); } STARTUPINFOW startInfo = {0}; startInfo.cb = sizeof(startInfo); startInfo.dwFlags = STARTF_USESTDHANDLES; startInfo.hStdInput = in.readSide.get(); startInfo.hStdOutput = out.writeSide.get(); startInfo.hStdError = out.writeSide.get(); std::string envline; // Retain the current processes' environment variables. for (const auto & envVar : getEnv()) { envline += (envVar.first + '=' + envVar.second + '\0'); } // Also add new ones specified in options. if (options.environment) { for (const auto & envVar : *options.environment) { envline += (envVar.first + '=' + envVar.second + '\0'); } } std::string cmdline = windowsEscape(realProgram, false); for (const auto & arg : options.args) { // TODO: This isn't the right way to escape windows command // See https://learn.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-commandlinetoargvw cmdline += ' ' + windowsEscape(arg, false); } PROCESS_INFORMATION procInfo = {0}; if (CreateProcessW( // EXE path is provided in the cmdline NULL, string_to_os_string(cmdline).data(), NULL, NULL, TRUE, CREATE_UNICODE_ENVIRONMENT | CREATE_SUSPENDED, string_to_os_string(envline).data(), options.chdir.has_value() ? string_to_os_string(*options.chdir).data() : NULL, &startInfo, &procInfo) == 0) { throw WinError("CreateProcessW failed (%1%)", cmdline); } // Convert these to use RAII AutoCloseFD process = procInfo.hProcess; AutoCloseFD thread = procInfo.hThread; // Add current process and child to job object so child terminates when parent terminates // TODO: This spawns one job per child process. We can probably keep this as a global, and // add children a single job so we don't use so many jobs at once. Descriptor job = CreateJobObjectW(NULL, NULL); if (job == NULL) { TerminateProcess(procInfo.hProcess, 0); throw WinError("Couldn't create job object for child process"); } if (AssignProcessToJobObject(job, procInfo.hProcess) == FALSE) { TerminateProcess(procInfo.hProcess, 0); throw WinError("Couldn't assign child process to job object"); } if (ResumeThread(procInfo.hThread) == (DWORD) -1) { TerminateProcess(procInfo.hProcess, 0); throw WinError("Couldn't resume child process thread"); } return process; } // TODO: Merge this with Unix's runProgram since it's identical logic. // Output = error code + "standard out" output stream std::pair<int, std::string> runProgram(RunOptions && options) { StringSink sink; options.standardOut = &sink; int status = 0; try { runProgram2(options); } catch (ExecError & e) { status = e.status; } return {status, std::move(sink.s)}; } void runProgram2(const RunOptions & options) { checkInterrupt(); assert(!(options.standardIn && options.input)); std::unique_ptr<Source> source_; Source * source = options.standardIn; if (options.input) { source_ = std::make_unique<StringSource>(*options.input); source = source_.get(); } /* Create a pipe. */ Pipe out, in; // TODO: I copied this from unix but this is handled again in spawnProcess, so might be weird to split it up like // this if (options.standardOut) out.create(); if (source) in.create(); Path realProgram = options.program; // TODO: Implement shebang / program interpreter lookup on Windows auto interpreter = getProgramInterpreter(realProgram); std::optional<Finally<std::function<void()>>> resumeLoggerDefer; if (options.isInteractive) { logger->pause(); resumeLoggerDefer.emplace([]() { logger->resume(); }); } Pid pid = spawnProcess(interpreter.has_value() ? *interpreter : realProgram, options, out, in); // TODO: This is identical to unix, deduplicate? out.writeSide.close(); std::thread writerThread; std::promise<void> promise; Finally doJoin([&] { if (writerThread.joinable()) writerThread.join(); }); if (source) { in.readSide.close(); writerThread = std::thread([&] { try { std::vector<char> buf(8 * 1024); while (true) { size_t n; try { n = source->read(buf.data(), buf.size()); } catch (EndOfFile &) { break; } writeFull(in.writeSide.get(), {buf.data(), n}); } promise.set_value(); } catch (...) { promise.set_exception(std::current_exception()); } in.writeSide.close(); }); } if (options.standardOut) drainFD(out.readSide.get(), *options.standardOut); /* Wait for the child to finish. */ int status = pid.wait(); /* Wait for the writer thread to finish. */ if (source) promise.get_future().get(); if (status) throw ExecError(status, "program '%1%' %2%", options.program, statusToString(status)); } std::string statusToString(int status) { if (status != 0) return fmt("with exit code %d", status); else return "succeeded"; } bool statusOk(int status) { return status == 0; } int execvpe(const wchar_t * file0, const wchar_t * const argv[], const wchar_t * const envp[]) { auto file = ExecutablePath::load().findPath(file0); return _wexecve(file.c_str(), argv, envp); } }
11,714
C++
.cc
331
29.081571
129
0.628995
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,916
muxable-pipe.cc
NixOS_nix/src/libutil/windows/muxable-pipe.cc
#include <ioapiset.h> #include "windows-error.hh" #include "logging.hh" #include "util.hh" #include "muxable-pipe.hh" namespace nix { void MuxablePipePollState::poll(HANDLE ioport, std::optional<unsigned int> timeout) { /* We are on at least Windows Vista / Server 2008 and can get many (countof(oentries)) statuses in one API call. */ if (!GetQueuedCompletionStatusEx( ioport, oentries, sizeof(oentries) / sizeof(*oentries), &removed, timeout ? *timeout : INFINITE, false)) { windows::WinError winError("GetQueuedCompletionStatusEx"); if (winError.lastError != WAIT_TIMEOUT) throw winError; assert(removed == 0); } else { assert(0 < removed && removed <= sizeof(oentries) / sizeof(*oentries)); } } void MuxablePipePollState::iterate( std::set<MuxablePipePollState::CommChannel> & channels, std::function<void(Descriptor fd, std::string_view data)> handleRead, std::function<void(Descriptor fd)> handleEOF) { auto p = channels.begin(); while (p != channels.end()) { decltype(p) nextp = p; ++nextp; for (ULONG i = 0; i < removed; i++) { if (oentries[i].lpCompletionKey == ((ULONG_PTR) ((*p)->readSide.get()) ^ 0x5555)) { printMsg(lvlVomit, "read %s bytes", oentries[i].dwNumberOfBytesTransferred); if (oentries[i].dwNumberOfBytesTransferred > 0) { std::string data{ (char *) (*p)->buffer.data(), oentries[i].dwNumberOfBytesTransferred, }; handleRead((*p)->readSide.get(), data); } if (gotEOF) { handleEOF((*p)->readSide.get()); nextp = channels.erase(p); // no need to maintain `channels`? } else { BOOL rc = ReadFile( (*p)->readSide.get(), (*p)->buffer.data(), (*p)->buffer.size(), &(*p)->got, &(*p)->overlapped); if (rc) { // here is possible (but not obligatory) to call // `handleRead` and repeat ReadFile immediately } else { windows::WinError winError("ReadFile(%s, ..)", (*p)->readSide.get()); if (winError.lastError == ERROR_BROKEN_PIPE) { handleEOF((*p)->readSide.get()); nextp = channels.erase(p); // no need to maintain `channels` ? } else if (winError.lastError != ERROR_IO_PENDING) throw winError; } } break; } } p = nextp; } } }
2,783
C++
.cc
64
30.90625
119
0.523406
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,917
file-descriptor.cc
NixOS_nix/src/libutil/windows/file-descriptor.cc
#include "file-system.hh" #include "signals.hh" #include "finally.hh" #include "serialise.hh" #include "windows-error.hh" #include "file-path.hh" #include <fileapi.h> #include <error.h> #include <namedpipeapi.h> #include <namedpipeapi.h> #define WIN32_LEAN_AND_MEAN #include <windows.h> namespace nix { using namespace nix::windows; std::string readFile(HANDLE handle) { LARGE_INTEGER li; if (!GetFileSizeEx(handle, &li)) throw WinError("%s:%d statting file", __FILE__, __LINE__); return drainFD(handle, true, li.QuadPart); } void readFull(HANDLE handle, char * buf, size_t count) { while (count) { checkInterrupt(); DWORD res; if (!ReadFile(handle, (char *) buf, count, &res, NULL)) throw WinError("%s:%d reading from file", __FILE__, __LINE__); if (res == 0) throw EndOfFile("unexpected end-of-file"); count -= res; buf += res; } } void writeFull(HANDLE handle, std::string_view s, bool allowInterrupts) { while (!s.empty()) { if (allowInterrupts) checkInterrupt(); DWORD res; #if _WIN32_WINNT >= 0x0600 auto path = handleToPath(handle); // debug; do it before becuase handleToPath changes lasterror if (!WriteFile(handle, s.data(), s.size(), &res, NULL)) { throw WinError("writing to file %1%:%2%", handle, path); } #else if (!WriteFile(handle, s.data(), s.size(), &res, NULL)) { throw WinError("writing to file %1%", handle); } #endif if (res > 0) s.remove_prefix(res); } } std::string readLine(HANDLE handle, bool eofOk) { std::string s; while (1) { checkInterrupt(); char ch; // FIXME: inefficient DWORD rd; if (!ReadFile(handle, &ch, 1, &rd, NULL)) { throw WinError("reading a line"); } else if (rd == 0) { if (eofOk) return s; else throw EndOfFile("unexpected EOF reading a line"); } else { if (ch == '\n') return s; s += ch; } } } void drainFD(HANDLE handle, Sink & sink/*, bool block*/) { std::vector<unsigned char> buf(64 * 1024); while (1) { checkInterrupt(); DWORD rd; if (!ReadFile(handle, buf.data(), buf.size(), &rd, NULL)) { WinError winError("%s:%d reading from handle %p", __FILE__, __LINE__, handle); if (winError.lastError == ERROR_BROKEN_PIPE) break; throw winError; } else if (rd == 0) break; sink({(char *) buf.data(), (size_t) rd}); } } ////////////////////////////////////////////////////////////////////// void Pipe::create() { SECURITY_ATTRIBUTES saAttr = {0}; saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.lpSecurityDescriptor = NULL; saAttr.bInheritHandle = TRUE; HANDLE hReadPipe, hWritePipe; if (!CreatePipe(&hReadPipe, &hWritePipe, &saAttr, 0)) throw WinError("CreatePipe"); readSide = hReadPipe; writeSide = hWritePipe; } ////////////////////////////////////////////////////////////////////// #if _WIN32_WINNT >= 0x0600 std::wstring windows::handleToFileName(HANDLE handle) { std::vector<wchar_t> buf(0x100); DWORD dw = GetFinalPathNameByHandleW(handle, buf.data(), buf.size(), FILE_NAME_OPENED); if (dw == 0) { if (handle == GetStdHandle(STD_INPUT_HANDLE )) return L"<stdin>"; if (handle == GetStdHandle(STD_OUTPUT_HANDLE)) return L"<stdout>"; if (handle == GetStdHandle(STD_ERROR_HANDLE )) return L"<stderr>"; return (boost::wformat(L"<unnnamed handle %X>") % handle).str(); } if (dw > buf.size()) { buf.resize(dw); if (GetFinalPathNameByHandleW(handle, buf.data(), buf.size(), FILE_NAME_OPENED) != dw-1) throw WinError("GetFinalPathNameByHandleW"); dw -= 1; } return std::wstring(buf.data(), dw); } Path windows::handleToPath(HANDLE handle) { return os_string_to_string(handleToFileName(handle)); } #endif }
4,103
C++
.cc
127
26.181102
103
0.578628
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,918
os-string.cc
NixOS_nix/src/libutil/windows/os-string.cc
#include <algorithm> #include <codecvt> #include <iostream> #include <locale> #include "file-path.hh" #include "file-path-impl.hh" #include "util.hh" namespace nix { std::string os_string_to_string(PathViewNG::string_view path) { std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; return converter.to_bytes(std::filesystem::path::string_type{path}); } std::filesystem::path::string_type string_to_os_string(std::string_view s) { std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; return converter.from_bytes(std::string{s}); } }
580
C++
.cc
19
28.421053
74
0.748201
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,919
users.cc
NixOS_nix/src/libutil/windows/users.cc
#include "util.hh" #include "users.hh" #include "environment-variables.hh" #include "file-system.hh" #include "windows-error.hh" #define WIN32_LEAN_AND_MEAN #include <windows.h> namespace nix { using namespace nix::windows; std::string getUserName() { // Get the required buffer size DWORD size = 0; if (!GetUserNameA(nullptr, &size)) { auto lastError = GetLastError(); if (lastError != ERROR_INSUFFICIENT_BUFFER) throw WinError(lastError, "cannot figure out size of user name"); } std::string name; // Allocate a buffer of sufficient size // // - 1 because no need for null byte name.resize(size - 1); // Retrieve the username if (!GetUserNameA(&name[0], &size)) throw WinError("cannot figure out user name"); return name; } Path getHome() { static Path homeDir = []() { Path homeDir = getEnv("USERPROFILE").value_or("C:\\Users\\Default"); assert(!homeDir.empty()); return canonPath(homeDir); }(); return homeDir; } bool isRootUser() { return false; } }
1,093
C++
.cc
42
21.738095
77
0.657061
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,920
file-path.cc
NixOS_nix/src/libutil/windows/file-path.cc
#include <algorithm> #include <codecvt> #include <iostream> #include <locale> #include "file-path.hh" #include "file-path-impl.hh" #include "util.hh" namespace nix { std::optional<std::filesystem::path> maybePath(PathView path) { if (path.length() >= 3 && (('A' <= path[0] && path[0] <= 'Z') || ('a' <= path[0] && path[0] <= 'z')) && path[1] == ':' && WindowsPathTrait<char>::isPathSep(path[2])) { std::filesystem::path::string_type sw = string_to_os_string( std::string { "\\\\?\\" } + path); std::replace(sw.begin(), sw.end(), '/', '\\'); return sw; } if (path.length() >= 7 && path[0] == '\\' && path[1] == '\\' && (path[2] == '.' || path[2] == '?') && path[3] == '\\' && ('A' <= path[4] && path[4] <= 'Z') && path[5] == ':' && WindowsPathTrait<char>::isPathSep(path[6])) { std::filesystem::path::string_type sw = string_to_os_string(path); std::replace(sw.begin(), sw.end(), '/', '\\'); return sw; } return std::optional<std::filesystem::path::string_type>(); } std::filesystem::path pathNG(PathView path) { std::optional<std::filesystem::path::string_type> sw = maybePath(path); if (!sw) { // FIXME why are we not using the regular error handling? std::cerr << "invalid path for WinAPI call ["<<path<<"]"<<std::endl; _exit(111); } return *sw; } }
1,392
C++
.cc
35
34.771429
171
0.546598
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,921
windows-error.cc
NixOS_nix/src/libutil/windows/windows-error.cc
#include "windows-error.hh" #include <error.h> #define WIN32_LEAN_AND_MEAN #include <windows.h> namespace nix::windows { std::string WinError::renderError(DWORD lastError) { LPSTR errorText = NULL; FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM // use system message tables to retrieve error text |FORMAT_MESSAGE_ALLOCATE_BUFFER // allocate buffer on local heap for error text |FORMAT_MESSAGE_IGNORE_INSERTS, // Important! will fail otherwise, since we're not (and CANNOT) pass insertion parameters NULL, // unused with FORMAT_MESSAGE_FROM_SYSTEM lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errorText, // output 0, // minimum size for output buffer NULL); // arguments - see note if (NULL != errorText ) { std::string s2 { errorText }; LocalFree(errorText); return s2; } return fmt("CODE=%d", lastError); } }
1,041
C++
.cc
25
32.32
143
0.614851
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,922
environment-variables.cc
NixOS_nix/src/libutil/windows/environment-variables.cc
#include "environment-variables.hh" #include "processenv.h" namespace nix { std::optional<OsString> getEnvOs(const OsString & key) { // Determine the required buffer size for the environment variable value DWORD bufferSize = GetEnvironmentVariableW(key.c_str(), nullptr, 0); if (bufferSize == 0) { return std::nullopt; } // Allocate a buffer to hold the environment variable value std::wstring value{bufferSize, L'\0'}; // Retrieve the environment variable value DWORD resultSize = GetEnvironmentVariableW(key.c_str(), &value[0], bufferSize); if (resultSize == 0) { return std::nullopt; } // Resize the string to remove the extra null characters value.resize(resultSize); return value; } int unsetenv(const char * name) { return -SetEnvironmentVariableA(name, nullptr); } int setEnv(const char * name, const char * value) { return -SetEnvironmentVariableA(name, value); } int setEnvOs(const OsString & name, const OsString & value) { return -SetEnvironmentVariableW(name.c_str(), value.c_str()); } }
1,091
C++
.cc
34
28.411765
83
0.717973
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,923
file-system.cc
NixOS_nix/src/libutil/windows/file-system.cc
#include "file-system.hh" namespace nix { Descriptor openDirectory(const std::filesystem::path & path) { return CreateFileW( path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); } }
332
C++
.cc
14
18.214286
63
0.638095
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,924
path.cc
NixOS_nix/src/libstore-test-support/tests/path.cc
#include <rapidcheck/gen/Arbitrary.h> #include <regex> #include <rapidcheck.h> #include "path-regex.hh" #include "store-api.hh" #include "tests/hash.hh" #include "tests/path.hh" namespace nix { void showValue(const StorePath & p, std::ostream & os) { os << p.to_string(); } } namespace rc { using namespace nix; Gen<char> storePathChar() { return rc::gen::apply([](uint8_t i) -> char { switch (i) { case 0 ... 9: return '0' + i; case 10 ... 35: return 'A' + (i - 10); case 36 ... 61: return 'a' + (i - 36); case 62: return '+'; case 63: return '-'; case 64: return '.'; case 65: return '_'; case 66: return '?'; case 67: return '='; default: assert(false); } }, gen::inRange<uint8_t>(0, 10 + 2 * 26 + 6)); } Gen<StorePathName> Arbitrary<StorePathName>::arbitrary() { return gen::construct<StorePathName>( gen::suchThat( gen::container<std::string>(storePathChar()), [](const std::string & s) { return !( s == "" || s == "." || s == ".." || s.starts_with(".-") || s.starts_with("..-") ); } ) ); } Gen<StorePath> Arbitrary<StorePath>::arbitrary() { return gen::construct<StorePath>( gen::arbitrary<Hash>(), gen::apply([](StorePathName n){ return n.name; }, gen::arbitrary<StorePathName>()) ); } } // namespace rc
1,774
C++
.cc
69
16.550725
94
0.448052
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,925
derived-path.cc
NixOS_nix/src/libstore-test-support/tests/derived-path.cc
#include <regex> #include <rapidcheck.h> #include "tests/derived-path.hh" namespace rc { using namespace nix; Gen<SingleDerivedPath::Opaque> Arbitrary<SingleDerivedPath::Opaque>::arbitrary() { return gen::just(DerivedPath::Opaque { .path = *gen::arbitrary<StorePath>(), }); } Gen<SingleDerivedPath::Built> Arbitrary<SingleDerivedPath::Built>::arbitrary() { return gen::just(SingleDerivedPath::Built { .drvPath = make_ref<SingleDerivedPath>(*gen::arbitrary<SingleDerivedPath>()), .output = (*gen::arbitrary<StorePathName>()).name, }); } Gen<DerivedPath::Built> Arbitrary<DerivedPath::Built>::arbitrary() { return gen::just(DerivedPath::Built { .drvPath = make_ref<SingleDerivedPath>(*gen::arbitrary<SingleDerivedPath>()), .outputs = *gen::arbitrary<OutputsSpec>(), }); } Gen<SingleDerivedPath> Arbitrary<SingleDerivedPath>::arbitrary() { switch (*gen::inRange<uint8_t>(0, std::variant_size_v<SingleDerivedPath::Raw>)) { case 0: return gen::just<SingleDerivedPath>(*gen::arbitrary<SingleDerivedPath::Opaque>()); case 1: return gen::just<SingleDerivedPath>(*gen::arbitrary<SingleDerivedPath::Built>()); default: assert(false); } } Gen<DerivedPath> Arbitrary<DerivedPath>::arbitrary() { switch (*gen::inRange<uint8_t>(0, std::variant_size_v<DerivedPath::Raw>)) { case 0: return gen::just<DerivedPath>(*gen::arbitrary<DerivedPath::Opaque>()); case 1: return gen::just<DerivedPath>(*gen::arbitrary<DerivedPath::Built>()); default: assert(false); } } }
1,607
C++
.cc
48
29.125
90
0.690323
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,926
outputs-spec.cc
NixOS_nix/src/libstore-test-support/tests/outputs-spec.cc
#include "tests/outputs-spec.hh" #include <rapidcheck.h> namespace rc { using namespace nix; Gen<OutputsSpec> Arbitrary<OutputsSpec>::arbitrary() { switch (*gen::inRange<uint8_t>(0, std::variant_size_v<OutputsSpec::Raw>)) { case 0: return gen::just((OutputsSpec) OutputsSpec::All { }); case 1: return gen::just((OutputsSpec) OutputsSpec::Names { *gen::nonEmpty(gen::container<StringSet>(gen::map( gen::arbitrary<StorePathName>(), [](StorePathName n) { return n.name; }))), }); default: assert(false); } } }
607
C++
.cc
20
24.35
79
0.617496
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,927
public-key.cc
NixOS_nix/src/libfetchers-tests/public-key.cc
#include <gtest/gtest.h> #include "fetchers.hh" #include "json-utils.hh" #include <nlohmann/json.hpp> #include "tests/characterization.hh" namespace nix { using nlohmann::json; class PublicKeyTest : public CharacterizationTest { std::filesystem::path unitTestData = getUnitTestData() / "public-key"; public: std::filesystem::path goldenMaster(std::string_view testStem) const override { return unitTestData / testStem; } }; #define TEST_JSON(FIXTURE, NAME, VAL) \ TEST_F(FIXTURE, PublicKey_ ## NAME ## _from_json) { \ readTest(#NAME ".json", [&](const auto & encoded_) { \ fetchers::PublicKey expected { VAL }; \ fetchers::PublicKey got = nlohmann::json::parse(encoded_); \ ASSERT_EQ(got, expected); \ }); \ } \ \ TEST_F(FIXTURE, PublicKey_ ## NAME ## _to_json) { \ writeTest(#NAME ".json", [&]() -> json { \ return nlohmann::json(fetchers::PublicKey { VAL }); \ }, [](const auto & file) { \ return json::parse(readFile(file)); \ }, [](const auto & file, const auto & got) { \ return writeFile(file, got.dump(2) + "\n"); \ }); \ } TEST_JSON(PublicKeyTest, simple, (fetchers::PublicKey { .type = "ssh-rsa", .key = "ABCDE" })) TEST_JSON(PublicKeyTest, defaultType, fetchers::PublicKey { .key = "ABCDE" }) #undef TEST_JSON TEST_F(PublicKeyTest, PublicKey_noRoundTrip_from_json) { readTest("noRoundTrip.json", [&](const auto & encoded_) { fetchers::PublicKey expected = { .type = "ssh-ed25519", .key = "ABCDE" }; fetchers::PublicKey got = nlohmann::json::parse(encoded_); ASSERT_EQ(got, expected); }); } }
2,255
C++
.cc
44
44.068182
93
0.463426
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,928
git-utils.cc
NixOS_nix/src/libfetchers-tests/git-utils.cc
#include "git-utils.hh" #include "file-system.hh" #include "gmock/gmock.h" #include <git2/global.h> #include <git2/repository.h> #include <git2/types.h> #include <gtest/gtest.h> #include "fs-sink.hh" #include "serialise.hh" namespace nix { class GitUtilsTest : public ::testing::Test { // We use a single repository for all tests. Path tmpDir; std::unique_ptr<AutoDelete> delTmpDir; public: void SetUp() override { tmpDir = createTempDir(); delTmpDir = std::make_unique<AutoDelete>(tmpDir, true); // Create the repo with libgit2 git_libgit2_init(); git_repository * repo = nullptr; auto r = git_repository_init(&repo, tmpDir.c_str(), 0); ASSERT_EQ(r, 0); git_repository_free(repo); } void TearDown() override { // Destroy the AutoDelete, triggering removal // not AutoDelete::reset(), which would cancel the deletion. delTmpDir.reset(); } ref<GitRepo> openRepo() { return GitRepo::openRepo(tmpDir, true, false); } }; void writeString(CreateRegularFileSink & fileSink, std::string contents, bool executable) { if (executable) fileSink.isExecutable(); fileSink.preallocateContents(contents.size()); fileSink(contents); } TEST_F(GitUtilsTest, sink_basic) { auto repo = openRepo(); auto sink = repo->getFileSystemObjectSink(); // TODO/Question: It seems a little odd that we use the tarball-like convention of requiring a top-level directory // here // The sync method does not document this behavior, should probably renamed because it's not very // general, and I can't imagine that "non-conventional" archives or any other source to be handled by // this sink. sink->createDirectory(CanonPath("foo-1.1")); sink->createRegularFile(CanonPath("foo-1.1/hello"), [](CreateRegularFileSink & fileSink) { writeString(fileSink, "hello world", false); }); sink->createRegularFile(CanonPath("foo-1.1/bye"), [](CreateRegularFileSink & fileSink) { writeString(fileSink, "thanks for all the fish", false); }); sink->createSymlink(CanonPath("foo-1.1/bye-link"), "bye"); sink->createDirectory(CanonPath("foo-1.1/empty")); sink->createDirectory(CanonPath("foo-1.1/links")); sink->createHardlink(CanonPath("foo-1.1/links/foo"), CanonPath("foo-1.1/hello")); // sink->createHardlink("foo-1.1/links/foo-2", CanonPath("foo-1.1/hello")); auto result = repo->dereferenceSingletonDirectory(sink->flush()); auto accessor = repo->getAccessor(result, false); auto entries = accessor->readDirectory(CanonPath::root); ASSERT_EQ(entries.size(), 5); ASSERT_EQ(accessor->readFile(CanonPath("hello")), "hello world"); ASSERT_EQ(accessor->readFile(CanonPath("bye")), "thanks for all the fish"); ASSERT_EQ(accessor->readLink(CanonPath("bye-link")), "bye"); ASSERT_EQ(accessor->readDirectory(CanonPath("empty")).size(), 0); ASSERT_EQ(accessor->readFile(CanonPath("links/foo")), "hello world"); }; TEST_F(GitUtilsTest, sink_hardlink) { auto repo = openRepo(); auto sink = repo->getFileSystemObjectSink(); sink->createDirectory(CanonPath("foo-1.1")); sink->createRegularFile(CanonPath("foo-1.1/hello"), [](CreateRegularFileSink & fileSink) { writeString(fileSink, "hello world", false); }); try { sink->createHardlink(CanonPath("foo-1.1/link"), CanonPath("hello")); FAIL() << "Expected an exception"; } catch (const nix::Error & e) { ASSERT_THAT(e.msg(), testing::HasSubstr("cannot find hard link target")); ASSERT_THAT(e.msg(), testing::HasSubstr("/hello")); ASSERT_THAT(e.msg(), testing::HasSubstr("foo-1.1/link")); } }; } // namespace nix
3,829
C++
.cc
94
35.670213
120
0.669357
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,929
graphml.cc
NixOS_nix/src/nix-store/graphml.cc
#include "graphml.hh" #include "store-api.hh" #include "derivations.hh" #include <iostream> using std::cout; namespace nix { static inline std::string_view xmlQuote(std::string_view s) { // Luckily, store paths shouldn't contain any character that needs to be // quoted. return s; } static std::string symbolicName(std::string_view p) { return std::string(p.substr(0, p.find('-') + 1)); } static std::string makeEdge(std::string_view src, std::string_view dst) { return fmt(" <edge source=\"%1%\" target=\"%2%\"/>\n", xmlQuote(src), xmlQuote(dst)); } static std::string makeNode(const ValidPathInfo & info) { return fmt( " <node id=\"%1%\">\n" " <data key=\"narSize\">%2%</data>\n" " <data key=\"name\">%3%</data>\n" " <data key=\"type\">%4%</data>\n" " </node>\n", info.path.to_string(), info.narSize, symbolicName(std::string(info.path.name())), (info.path.isDerivation() ? "derivation" : "output-path")); } void printGraphML(ref<Store> store, StorePathSet && roots) { StorePathSet workList(std::move(roots)); StorePathSet doneSet; std::pair<StorePathSet::iterator, bool> ret; cout << "<?xml version='1.0' encoding='utf-8'?>\n" << "<graphml xmlns='http://graphml.graphdrawing.org/xmlns'\n" << " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'\n" << " xsi:schemaLocation='http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd'>\n" << "<key id='narSize' for='node' attr.name='narSize' attr.type='long'/>" << "<key id='name' for='node' attr.name='name' attr.type='string'/>" << "<key id='type' for='node' attr.name='type' attr.type='string'/>" << "<graph id='G' edgedefault='directed'>\n"; while (!workList.empty()) { auto path = std::move(workList.extract(workList.begin()).value()); ret = doneSet.insert(path); if (ret.second == false) continue; auto info = store->queryPathInfo(path); cout << makeNode(*info); for (auto & p : info->references) { if (p != path) { workList.insert(p); cout << makeEdge(path.to_string(), p.to_string()); } } } cout << "</graph>\n"; cout << "</graphml>\n"; } }
2,350
C++
.cc
64
30.5
95
0.585506
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
10,930
nix-store.cc
NixOS_nix/src/nix-store/nix-store.cc
#include "archive.hh" #include "derivations.hh" #include "dotgraph.hh" #include "globals.hh" #include "store-cast.hh" #include "local-fs-store.hh" #include "log-store.hh" #include "serve-protocol.hh" #include "serve-protocol-connection.hh" #include "shared.hh" #include "graphml.hh" #include "legacy.hh" #include "posix-source-accessor.hh" #include "path-with-outputs.hh" #ifndef _WIN32 // TODO implement on Windows or provide allowed-to-noop interface # include "local-store.hh" # include "monitor-fd.hh" # include "posix-fs-canonicalise.hh" #endif #include <iostream> #include <algorithm> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "build-result.hh" #include "exit.hh" #include "serve-protocol-impl.hh" namespace nix_store { using namespace nix; using std::cin; using std::cout; typedef void (* Operation) (Strings opFlags, Strings opArgs); static Path gcRoot; static int rootNr = 0; static bool noOutput = false; static std::shared_ptr<Store> store; #ifndef _WIN32 // TODO reenable on Windows once we have `LocalStore` there ref<LocalStore> ensureLocalStore() { auto store2 = std::dynamic_pointer_cast<LocalStore>(store); if (!store2) throw Error("you don't have sufficient rights to use this command"); return ref<LocalStore>(store2); } #endif static StorePath useDeriver(const StorePath & path) { if (path.isDerivation()) return path; auto info = store->queryPathInfo(path); if (!info->deriver) throw Error("deriver of path '%s' is not known", store->printStorePath(path)); return *info->deriver; } /* Realise the given path. For a derivation that means build it; for other paths it means ensure their validity. */ static PathSet realisePath(StorePathWithOutputs path, bool build = true) { auto store2 = std::dynamic_pointer_cast<LocalFSStore>(store); if (path.path.isDerivation()) { if (build) store->buildPaths({path.toDerivedPath()}); auto outputPaths = store->queryDerivationOutputMap(path.path); Derivation drv = store->derivationFromPath(path.path); rootNr++; /* FIXME: Encode this empty special case explicitly in the type. */ if (path.outputs.empty()) for (auto & i : drv.outputs) path.outputs.insert(i.first); PathSet outputs; for (auto & j : path.outputs) { /* Match outputs of a store path with outputs of the derivation that produces it. */ DerivationOutputs::iterator i = drv.outputs.find(j); if (i == drv.outputs.end()) throw Error("derivation '%s' does not have an output named '%s'", store2->printStorePath(path.path), j); auto outPath = outputPaths.at(i->first); auto retPath = store->printStorePath(outPath); if (store2) { if (gcRoot == "") printGCWarning(); else { Path rootName = gcRoot; if (rootNr > 1) rootName += "-" + std::to_string(rootNr); if (i->first != "out") rootName += "-" + i->first; retPath = store2->addPermRoot(outPath, rootName); } } outputs.insert(retPath); } return outputs; } else { if (build) store->ensurePath(path.path); else if (!store->isValidPath(path.path)) throw Error("path '%s' does not exist and cannot be created", store->printStorePath(path.path)); if (store2) { if (gcRoot == "") printGCWarning(); else { Path rootName = gcRoot; rootNr++; if (rootNr > 1) rootName += "-" + std::to_string(rootNr); return {store2->addPermRoot(path.path, rootName)}; } } return {store->printStorePath(path.path)}; } } /* Realise the given paths. */ static void opRealise(Strings opFlags, Strings opArgs) { bool dryRun = false; BuildMode buildMode = bmNormal; bool ignoreUnknown = false; for (auto & i : opFlags) if (i == "--dry-run") dryRun = true; else if (i == "--repair") buildMode = bmRepair; else if (i == "--check") buildMode = bmCheck; else if (i == "--ignore-unknown") ignoreUnknown = true; else throw UsageError("unknown flag '%1%'", i); std::vector<StorePathWithOutputs> paths; for (auto & i : opArgs) paths.push_back(followLinksToStorePathWithOutputs(*store, i)); uint64_t downloadSize, narSize; StorePathSet willBuild, willSubstitute, unknown; store->queryMissing( toDerivedPaths(paths), willBuild, willSubstitute, unknown, downloadSize, narSize); /* Filter out unknown paths from `paths`. */ if (ignoreUnknown) { std::vector<StorePathWithOutputs> paths2; for (auto & i : paths) if (!unknown.count(i.path)) paths2.push_back(i); paths = std::move(paths2); unknown = StorePathSet(); } if (settings.printMissing) printMissing(ref<Store>(store), willBuild, willSubstitute, unknown, downloadSize, narSize); if (dryRun) return; /* Build all paths at the same time to exploit parallelism. */ store->buildPaths(toDerivedPaths(paths), buildMode); if (!ignoreUnknown) for (auto & i : paths) { auto paths2 = realisePath(i, false); if (!noOutput) for (auto & j : paths2) cout << fmt("%1%\n", j); } } /* Add files to the Nix store and print the resulting paths. */ static void opAdd(Strings opFlags, Strings opArgs) { if (!opFlags.empty()) throw UsageError("unknown flag"); for (auto & i : opArgs) { auto [accessor, canonPath] = PosixSourceAccessor::createAtRoot(i); cout << fmt("%s\n", store->printStorePath(store->addToStore( std::string(baseNameOf(i)), {accessor, canonPath}))); } } /* Preload the output of a fixed-output derivation into the Nix store. */ static void opAddFixed(Strings opFlags, Strings opArgs) { ContentAddressMethod method = ContentAddressMethod::Raw::Flat; for (auto & i : opFlags) if (i == "--recursive") method = ContentAddressMethod::Raw::NixArchive; else throw UsageError("unknown flag '%1%'", i); if (opArgs.empty()) throw UsageError("first argument must be hash algorithm"); HashAlgorithm hashAlgo = parseHashAlgo(opArgs.front()); opArgs.pop_front(); for (auto & i : opArgs) { auto [accessor, canonPath] = PosixSourceAccessor::createAtRoot(i); std::cout << fmt("%s\n", store->printStorePath(store->addToStoreSlow( baseNameOf(i), {accessor, canonPath}, method, hashAlgo).path)); } } /* Hack to support caching in `nix-prefetch-url'. */ static void opPrintFixedPath(Strings opFlags, Strings opArgs) { auto method = FileIngestionMethod::Flat; for (auto i : opFlags) if (i == "--recursive") method = FileIngestionMethod::NixArchive; else throw UsageError("unknown flag '%1%'", i); if (opArgs.size() != 3) throw UsageError("'--print-fixed-path' requires three arguments"); Strings::iterator i = opArgs.begin(); HashAlgorithm hashAlgo = parseHashAlgo(*i++); std::string hash = *i++; std::string name = *i++; cout << fmt("%s\n", store->printStorePath(store->makeFixedOutputPath(name, FixedOutputInfo { .method = method, .hash = Hash::parseAny(hash, hashAlgo), .references = {}, }))); } static StorePathSet maybeUseOutputs(const StorePath & storePath, bool useOutput, bool forceRealise) { if (forceRealise) realisePath({storePath}); if (useOutput && storePath.isDerivation()) { auto drv = store->derivationFromPath(storePath); StorePathSet outputs; if (forceRealise) return store->queryDerivationOutputs(storePath); for (auto & i : drv.outputsAndOptPaths(*store)) { if (!i.second.second) throw UsageError("Cannot use output path of floating content-addressed derivation until we know what it is (e.g. by building it)"); outputs.insert(*i.second.second); } return outputs; } else return {storePath}; } /* Some code to print a tree representation of a derivation dependency graph. Topological sorting is used to keep the tree relatively flat. */ static void printTree(const StorePath & path, const std::string & firstPad, const std::string & tailPad, StorePathSet & done) { if (!done.insert(path).second) { cout << fmt("%s%s [...]\n", firstPad, store->printStorePath(path)); return; } cout << fmt("%s%s\n", firstPad, store->printStorePath(path)); auto info = store->queryPathInfo(path); /* Topologically sort under the relation A < B iff A \in closure(B). That is, if derivation A is an (possibly indirect) input of B, then A is printed first. This has the effect of flattening the tree, preventing deeply nested structures. */ auto sorted = store->topoSortPaths(info->references); reverse(sorted.begin(), sorted.end()); for (const auto &[n, i] : enumerate(sorted)) { bool last = n + 1 == sorted.size(); printTree(i, tailPad + (last ? treeLast : treeConn), tailPad + (last ? treeNull : treeLine), done); } } /* Perform various sorts of queries. */ static void opQuery(Strings opFlags, Strings opArgs) { enum QueryType { qOutputs, qRequisites, qReferences, qReferrers , qReferrersClosure, qDeriver, qValidDerivers, qBinding, qHash, qSize , qTree, qGraph, qGraphML, qResolve, qRoots }; std::optional<QueryType> query; bool useOutput = false; bool includeOutputs = false; bool forceRealise = false; std::string bindingName; for (auto & i : opFlags) { std::optional<QueryType> prev = query; if (i == "--outputs") query = qOutputs; else if (i == "--requisites" || i == "-R") query = qRequisites; else if (i == "--references") query = qReferences; else if (i == "--referrers" || i == "--referers") query = qReferrers; else if (i == "--referrers-closure" || i == "--referers-closure") query = qReferrersClosure; else if (i == "--deriver" || i == "-d") query = qDeriver; else if (i == "--valid-derivers") query = qValidDerivers; else if (i == "--binding" || i == "-b") { if (opArgs.size() == 0) throw UsageError("expected binding name"); bindingName = opArgs.front(); opArgs.pop_front(); query = qBinding; } else if (i == "--hash") query = qHash; else if (i == "--size") query = qSize; else if (i == "--tree") query = qTree; else if (i == "--graph") query = qGraph; else if (i == "--graphml") query = qGraphML; else if (i == "--resolve") query = qResolve; else if (i == "--roots") query = qRoots; else if (i == "--use-output" || i == "-u") useOutput = true; else if (i == "--force-realise" || i == "--force-realize" || i == "-f") forceRealise = true; else if (i == "--include-outputs") includeOutputs = true; else throw UsageError("unknown flag '%1%'", i); if (prev && prev != query) throw UsageError("query type '%1%' conflicts with earlier flag", i); } if (!query) query = qOutputs; RunPager pager; switch (*query) { case qOutputs: { for (auto & i : opArgs) { auto outputs = maybeUseOutputs(store->followLinksToStorePath(i), true, forceRealise); for (auto & outputPath : outputs) cout << fmt("%1%\n", store->printStorePath(outputPath)); } break; } case qRequisites: case qReferences: case qReferrers: case qReferrersClosure: { StorePathSet paths; for (auto & i : opArgs) { auto ps = maybeUseOutputs(store->followLinksToStorePath(i), useOutput, forceRealise); for (auto & j : ps) { if (query == qRequisites) store->computeFSClosure(j, paths, false, includeOutputs); else if (query == qReferences) { for (auto & p : store->queryPathInfo(j)->references) paths.insert(p); } else if (query == qReferrers) { StorePathSet tmp; store->queryReferrers(j, tmp); for (auto & i : tmp) paths.insert(i); } else if (query == qReferrersClosure) store->computeFSClosure(j, paths, true); } } auto sorted = store->topoSortPaths(paths); for (StorePaths::reverse_iterator i = sorted.rbegin(); i != sorted.rend(); ++i) cout << fmt("%s\n", store->printStorePath(*i)); break; } case qDeriver: for (auto & i : opArgs) { auto info = store->queryPathInfo(store->followLinksToStorePath(i)); cout << fmt("%s\n", info->deriver ? store->printStorePath(*info->deriver) : "unknown-deriver"); } break; case qValidDerivers: { StorePathSet result; for (auto & i : opArgs) { auto derivers = store->queryValidDerivers(store->followLinksToStorePath(i)); for (const auto &i: derivers) { result.insert(i); } } auto sorted = store->topoSortPaths(result); for (StorePaths::reverse_iterator i = sorted.rbegin(); i != sorted.rend(); ++i) cout << fmt("%s\n", store->printStorePath(*i)); break; } case qBinding: for (auto & i : opArgs) { auto path = useDeriver(store->followLinksToStorePath(i)); Derivation drv = store->derivationFromPath(path); StringPairs::iterator j = drv.env.find(bindingName); if (j == drv.env.end()) throw Error("derivation '%s' has no environment binding named '%s'", store->printStorePath(path), bindingName); cout << fmt("%s\n", j->second); } break; case qHash: case qSize: for (auto & i : opArgs) { for (auto & j : maybeUseOutputs(store->followLinksToStorePath(i), useOutput, forceRealise)) { auto info = store->queryPathInfo(j); if (query == qHash) { assert(info->narHash.algo == HashAlgorithm::SHA256); cout << fmt("%s\n", info->narHash.to_string(HashFormat::Nix32, true)); } else if (query == qSize) cout << fmt("%d\n", info->narSize); } } break; case qTree: { StorePathSet done; for (auto & i : opArgs) printTree(store->followLinksToStorePath(i), "", "", done); break; } case qGraph: { StorePathSet roots; for (auto & i : opArgs) for (auto & j : maybeUseOutputs(store->followLinksToStorePath(i), useOutput, forceRealise)) roots.insert(j); printDotGraph(ref<Store>(store), std::move(roots)); break; } case qGraphML: { StorePathSet roots; for (auto & i : opArgs) for (auto & j : maybeUseOutputs(store->followLinksToStorePath(i), useOutput, forceRealise)) roots.insert(j); printGraphML(ref<Store>(store), std::move(roots)); break; } case qResolve: { for (auto & i : opArgs) cout << fmt("%s\n", store->printStorePath(store->followLinksToStorePath(i))); break; } case qRoots: { StorePathSet args; for (auto & i : opArgs) for (auto & p : maybeUseOutputs(store->followLinksToStorePath(i), useOutput, forceRealise)) args.insert(p); StorePathSet referrers; store->computeFSClosure( args, referrers, true, settings.gcKeepOutputs, settings.gcKeepDerivations); auto & gcStore = require<GcStore>(*store); Roots roots = gcStore.findRoots(false); for (auto & [target, links] : roots) if (referrers.find(target) != referrers.end()) for (auto & link : links) cout << fmt("%1% -> %2%\n", link, gcStore.printStorePath(target)); break; } default: unreachable(); } } static void opPrintEnv(Strings opFlags, Strings opArgs) { if (!opFlags.empty()) throw UsageError("unknown flag"); if (opArgs.size() != 1) throw UsageError("'--print-env' requires one derivation store path"); Path drvPath = opArgs.front(); Derivation drv = store->derivationFromPath(store->parseStorePath(drvPath)); /* Print each environment variable in the derivation in a format * that can be sourced by the shell. */ for (auto & i : drv.env) logger->cout("export %1%; %1%=%2%\n", i.first, shellEscape(i.second)); /* Also output the arguments. This doesn't preserve whitespace in arguments. */ cout << "export _args; _args='"; bool first = true; for (auto & i : drv.args) { if (!first) cout << ' '; first = false; cout << shellEscape(i); } cout << "'\n"; } static void opReadLog(Strings opFlags, Strings opArgs) { if (!opFlags.empty()) throw UsageError("unknown flag"); auto & logStore = require<LogStore>(*store); RunPager pager; for (auto & i : opArgs) { auto path = logStore.followLinksToStorePath(i); auto log = logStore.getBuildLog(path); if (!log) throw Error("build log of derivation '%s' is not available", logStore.printStorePath(path)); std::cout << *log; } } static void opDumpDB(Strings opFlags, Strings opArgs) { if (!opFlags.empty()) throw UsageError("unknown flag"); if (!opArgs.empty()) { for (auto & i : opArgs) cout << store->makeValidityRegistration({store->followLinksToStorePath(i)}, true, true); } else { for (auto & i : store->queryAllValidPaths()) cout << store->makeValidityRegistration({i}, true, true); } } static void registerValidity(bool reregister, bool hashGiven, bool canonicalise) { ValidPathInfos infos; while (1) { // We use a dummy value because we'll set it below. FIXME be correct by // construction and avoid dummy value. auto hashResultOpt = !hashGiven ? std::optional<HashResult> { {Hash::dummy, -1} } : std::nullopt; auto info = decodeValidPathInfo(*store, cin, hashResultOpt); if (!info) break; if (!store->isValidPath(info->path) || reregister) { /* !!! races */ if (canonicalise) #ifdef _WIN32 // TODO implement on Windows throw UnimplementedError("file attribute canonicalisation Is not implemented on Windows"); #else canonicalisePathMetaData(store->printStorePath(info->path), {}); #endif if (!hashGiven) { HashResult hash = hashPath( {store->getFSAccessor(false), CanonPath { store->printStorePath(info->path) }}, FileSerialisationMethod::NixArchive, HashAlgorithm::SHA256); info->narHash = hash.first; info->narSize = hash.second; } infos.insert_or_assign(info->path, *info); } } #ifndef _WIN32 // TODO reenable on Windows once we have `LocalStore` there ensureLocalStore()->registerValidPaths(infos); #endif } static void opLoadDB(Strings opFlags, Strings opArgs) { if (!opFlags.empty()) throw UsageError("unknown flag"); if (!opArgs.empty()) throw UsageError("no arguments expected"); registerValidity(true, true, false); } static void opRegisterValidity(Strings opFlags, Strings opArgs) { bool reregister = false; // !!! maybe this should be the default bool hashGiven = false; for (auto & i : opFlags) if (i == "--reregister") reregister = true; else if (i == "--hash-given") hashGiven = true; else throw UsageError("unknown flag '%1%'", i); if (!opArgs.empty()) throw UsageError("no arguments expected"); registerValidity(reregister, hashGiven, true); } static void opCheckValidity(Strings opFlags, Strings opArgs) { bool printInvalid = false; for (auto & i : opFlags) if (i == "--print-invalid") printInvalid = true; else throw UsageError("unknown flag '%1%'", i); for (auto & i : opArgs) { auto path = store->followLinksToStorePath(i); if (!store->isValidPath(path)) { if (printInvalid) cout << fmt("%s\n", store->printStorePath(path)); else throw Error("path '%s' is not valid", store->printStorePath(path)); } } } static void opGC(Strings opFlags, Strings opArgs) { bool printRoots = false; GCOptions options; options.action = GCOptions::gcDeleteDead; GCResults results; /* Do what? */ for (auto i = opFlags.begin(); i != opFlags.end(); ++i) if (*i == "--print-roots") printRoots = true; else if (*i == "--print-live") options.action = GCOptions::gcReturnLive; else if (*i == "--print-dead") options.action = GCOptions::gcReturnDead; else if (*i == "--max-freed") options.maxFreed = std::max(getIntArg<int64_t>(*i, i, opFlags.end(), true), (int64_t) 0); else throw UsageError("bad sub-operation '%1%' in GC", *i); if (!opArgs.empty()) throw UsageError("no arguments expected"); auto & gcStore = require<GcStore>(*store); if (printRoots) { Roots roots = gcStore.findRoots(false); std::set<std::pair<Path, StorePath>> roots2; // Transpose and sort the roots. for (auto & [target, links] : roots) for (auto & link : links) roots2.emplace(link, target); for (auto & [link, target] : roots2) std::cout << link << " -> " << gcStore.printStorePath(target) << "\n"; } else { PrintFreed freed(options.action == GCOptions::gcDeleteDead, results); gcStore.collectGarbage(options, results); if (options.action != GCOptions::gcDeleteDead) for (auto & i : results.paths) cout << i << std::endl; } } /* Remove paths from the Nix store if possible (i.e., if they do not have any remaining referrers and are not reachable from any GC roots). */ static void opDelete(Strings opFlags, Strings opArgs) { GCOptions options; options.action = GCOptions::gcDeleteSpecific; for (auto & i : opFlags) if (i == "--ignore-liveness") options.ignoreLiveness = true; else throw UsageError("unknown flag '%1%'", i); for (auto & i : opArgs) options.pathsToDelete.insert(store->followLinksToStorePath(i)); auto & gcStore = require<GcStore>(*store); GCResults results; PrintFreed freed(true, results); gcStore.collectGarbage(options, results); } /* Dump a path as a Nix archive. The archive is written to stdout */ static void opDump(Strings opFlags, Strings opArgs) { if (!opFlags.empty()) throw UsageError("unknown flag"); if (opArgs.size() != 1) throw UsageError("only one argument allowed"); FdSink sink(getStandardOutput()); std::string path = *opArgs.begin(); dumpPath(path, sink); sink.flush(); } /* Restore a value from a Nix archive. The archive is read from stdin. */ static void opRestore(Strings opFlags, Strings opArgs) { if (!opFlags.empty()) throw UsageError("unknown flag"); if (opArgs.size() != 1) throw UsageError("only one argument allowed"); FdSource source(STDIN_FILENO); restorePath(*opArgs.begin(), source); } static void opExport(Strings opFlags, Strings opArgs) { for (auto & i : opFlags) throw UsageError("unknown flag '%1%'", i); StorePathSet paths; for (auto & i : opArgs) paths.insert(store->followLinksToStorePath(i)); FdSink sink(getStandardOutput()); store->exportPaths(paths, sink); sink.flush(); } static void opImport(Strings opFlags, Strings opArgs) { for (auto & i : opFlags) throw UsageError("unknown flag '%1%'", i); if (!opArgs.empty()) throw UsageError("no arguments expected"); FdSource source(STDIN_FILENO); auto paths = store->importPaths(source, NoCheckSigs); for (auto & i : paths) cout << fmt("%s\n", store->printStorePath(i)) << std::flush; } /* Initialise the Nix databases. */ static void opInit(Strings opFlags, Strings opArgs) { if (!opFlags.empty()) throw UsageError("unknown flag"); if (!opArgs.empty()) throw UsageError("no arguments expected"); /* Doesn't do anything right now; database tables are initialised automatically. */ } /* Verify the consistency of the Nix environment. */ static void opVerify(Strings opFlags, Strings opArgs) { if (!opArgs.empty()) throw UsageError("no arguments expected"); bool checkContents = false; RepairFlag repair = NoRepair; for (auto & i : opFlags) if (i == "--check-contents") checkContents = true; else if (i == "--repair") repair = Repair; else throw UsageError("unknown flag '%1%'", i); if (store->verifyStore(checkContents, repair)) { warn("not all store errors were fixed"); throw Exit(1); } } /* Verify whether the contents of the given store path have not changed. */ static void opVerifyPath(Strings opFlags, Strings opArgs) { if (!opFlags.empty()) throw UsageError("no flags expected"); int status = 0; for (auto & i : opArgs) { auto path = store->followLinksToStorePath(i); printMsg(lvlTalkative, "checking path '%s'...", store->printStorePath(path)); auto info = store->queryPathInfo(path); HashSink sink(info->narHash.algo); store->narFromPath(path, sink); auto current = sink.finish(); if (current.first != info->narHash) { printError("path '%s' was modified! expected hash '%s', got '%s'", store->printStorePath(path), info->narHash.to_string(HashFormat::Nix32, true), current.first.to_string(HashFormat::Nix32, true)); status = 1; } } throw Exit(status); } /* Repair the contents of the given path by redownloading it using a substituter (if available). */ static void opRepairPath(Strings opFlags, Strings opArgs) { if (!opFlags.empty()) throw UsageError("no flags expected"); for (auto & i : opArgs) store->repairPath(store->followLinksToStorePath(i)); } /* Optimise the disk space usage of the Nix store by hard-linking files with the same contents. */ static void opOptimise(Strings opFlags, Strings opArgs) { if (!opArgs.empty() || !opFlags.empty()) throw UsageError("no arguments expected"); store->optimiseStore(); } /* Serve the nix store in a way usable by a restricted ssh user. */ static void opServe(Strings opFlags, Strings opArgs) { bool writeAllowed = false; for (auto & i : opFlags) if (i == "--write") writeAllowed = true; else throw UsageError("unknown flag '%1%'", i); if (!opArgs.empty()) throw UsageError("no arguments expected"); FdSource in(STDIN_FILENO); FdSink out(getStandardOutput()); /* Exchange the greeting. */ ServeProto::Version clientVersion = ServeProto::BasicServerConnection::handshake( out, in, SERVE_PROTOCOL_VERSION); ServeProto::ReadConn rconn { .from = in, .version = clientVersion, }; ServeProto::WriteConn wconn { .to = out, .version = clientVersion, }; auto getBuildSettings = [&]() { // FIXME: changing options here doesn't work if we're // building through the daemon. verbosity = lvlError; settings.keepLog = false; settings.useSubstitutes = false; auto options = ServeProto::Serialise<ServeProto::BuildOptions>::read(*store, rconn); // Only certain feilds get initialized based on the protocol // version. This is why not all the code below is unconditional. // See how the serialization logic in // `ServeProto::Serialise<ServeProto::BuildOptions>` matches // these conditions. settings.maxSilentTime = options.maxSilentTime; settings.buildTimeout = options.buildTimeout; if (GET_PROTOCOL_MINOR(clientVersion) >= 2) settings.maxLogSize = options.maxLogSize; if (GET_PROTOCOL_MINOR(clientVersion) >= 3) { if (options.nrRepeats != 0) { throw Error("client requested repeating builds, but this is not currently implemented"); } // Ignore 'options.enforceDeterminism'. // // It used to be true by default, but also only never had // any effect when `nrRepeats == 0`. We have already // checked that `nrRepeats` in fact is 0, so we can safely // ignore this without doing something other than what the // client asked for. settings.runDiffHook = true; } if (GET_PROTOCOL_MINOR(clientVersion) >= 7) { settings.keepFailed = options.keepFailed; } }; while (true) { ServeProto::Command cmd; try { cmd = (ServeProto::Command) readInt(in); } catch (EndOfFile & e) { break; } switch (cmd) { case ServeProto::Command::QueryValidPaths: { bool lock = readInt(in); bool substitute = readInt(in); auto paths = ServeProto::Serialise<StorePathSet>::read(*store, rconn); if (lock && writeAllowed) for (auto & path : paths) store->addTempRoot(path); if (substitute && writeAllowed) { store->substitutePaths(paths); } ServeProto::write(*store, wconn, store->queryValidPaths(paths)); break; } case ServeProto::Command::QueryPathInfos: { auto paths = ServeProto::Serialise<StorePathSet>::read(*store, rconn); // !!! Maybe we want a queryPathInfos? for (auto & i : paths) { try { auto info = store->queryPathInfo(i); out << store->printStorePath(info->path); ServeProto::write(*store, wconn, static_cast<const UnkeyedValidPathInfo &>(*info)); } catch (InvalidPath &) { } } out << ""; break; } case ServeProto::Command::DumpStorePath: store->narFromPath(store->parseStorePath(readString(in)), out); break; case ServeProto::Command::ImportPaths: { if (!writeAllowed) throw Error("importing paths is not allowed"); store->importPaths(in, NoCheckSigs); // FIXME: should we skip sig checking? out << 1; // indicate success break; } case ServeProto::Command::ExportPaths: { readInt(in); // obsolete store->exportPaths(ServeProto::Serialise<StorePathSet>::read(*store, rconn), out); break; } case ServeProto::Command::BuildPaths: { if (!writeAllowed) throw Error("building paths is not allowed"); std::vector<StorePathWithOutputs> paths; for (auto & s : readStrings<Strings>(in)) paths.push_back(parsePathWithOutputs(*store, s)); getBuildSettings(); try { #ifndef _WIN32 // TODO figure out if Windows needs something similar MonitorFdHup monitor(in.fd); #endif store->buildPaths(toDerivedPaths(paths)); out << 0; } catch (Error & e) { assert(e.info().status); out << e.info().status << e.msg(); } break; } case ServeProto::Command::BuildDerivation: { /* Used by hydra-queue-runner. */ if (!writeAllowed) throw Error("building paths is not allowed"); auto drvPath = store->parseStorePath(readString(in)); BasicDerivation drv; readDerivation(in, *store, drv, Derivation::nameFromPath(drvPath)); getBuildSettings(); #ifndef _WIN32 // TODO figure out if Windows needs something similar MonitorFdHup monitor(in.fd); #endif auto status = store->buildDerivation(drvPath, drv); ServeProto::write(*store, wconn, status); break; } case ServeProto::Command::QueryClosure: { bool includeOutputs = readInt(in); StorePathSet closure; store->computeFSClosure(ServeProto::Serialise<StorePathSet>::read(*store, rconn), closure, false, includeOutputs); ServeProto::write(*store, wconn, closure); break; } case ServeProto::Command::AddToStoreNar: { if (!writeAllowed) throw Error("importing paths is not allowed"); auto path = readString(in); auto deriver = readString(in); ValidPathInfo info { store->parseStorePath(path), Hash::parseAny(readString(in), HashAlgorithm::SHA256), }; if (deriver != "") info.deriver = store->parseStorePath(deriver); info.references = ServeProto::Serialise<StorePathSet>::read(*store, rconn); in >> info.registrationTime >> info.narSize >> info.ultimate; info.sigs = readStrings<StringSet>(in); info.ca = ContentAddress::parseOpt(readString(in)); if (info.narSize == 0) throw Error("narInfo is too old and missing the narSize field"); SizedSource sizedSource(in, info.narSize); store->addToStore(info, sizedSource, NoRepair, NoCheckSigs); // consume all the data that has been sent before continuing. sizedSource.drainAll(); out << 1; // indicate success break; } default: throw Error("unknown serve command %1%", cmd); } out.flush(); } } static void opGenerateBinaryCacheKey(Strings opFlags, Strings opArgs) { for (auto & i : opFlags) throw UsageError("unknown flag '%1%'", i); if (opArgs.size() != 3) throw UsageError("three arguments expected"); auto i = opArgs.begin(); std::string keyName = *i++; std::string secretKeyFile = *i++; std::string publicKeyFile = *i++; auto secretKey = SecretKey::generate(keyName); writeFile(publicKeyFile, secretKey.toPublicKey().to_string()); umask(0077); writeFile(secretKeyFile, secretKey.to_string()); } static void opVersion(Strings opFlags, Strings opArgs) { printVersion("nix-store"); } /* Scan the arguments; find the operation, set global flags, put all other flags in a list, and put all other arguments in another list. */ static int main_nix_store(int argc, char * * argv) { { Strings opFlags, opArgs; Operation op = 0; bool readFromStdIn = false; std::string opName; bool showHelp = false; parseCmdLine(argc, argv, [&](Strings::iterator & arg, const Strings::iterator & end) { Operation oldOp = op; if (*arg == "--help") showHelp = true; else if (*arg == "--version") op = opVersion; else if (*arg == "--realise" || *arg == "--realize" || *arg == "-r") { op = opRealise; opName = "-realise"; } else if (*arg == "--add" || *arg == "-A"){ op = opAdd; opName = "-add"; } else if (*arg == "--add-fixed") { op = opAddFixed; opName = arg->substr(1); } else if (*arg == "--print-fixed-path") op = opPrintFixedPath; else if (*arg == "--delete") { op = opDelete; opName = arg->substr(1); } else if (*arg == "--query" || *arg == "-q") { op = opQuery; opName = "-query"; } else if (*arg == "--print-env") { op = opPrintEnv; opName = arg->substr(1); } else if (*arg == "--read-log" || *arg == "-l") { op = opReadLog; opName = "-read-log"; } else if (*arg == "--dump-db") { op = opDumpDB; opName = arg->substr(1); } else if (*arg == "--load-db") { op = opLoadDB; opName = arg->substr(1); } else if (*arg == "--register-validity") op = opRegisterValidity; else if (*arg == "--check-validity") op = opCheckValidity; else if (*arg == "--gc") { op = opGC; opName = arg->substr(1); } else if (*arg == "--dump") { op = opDump; opName = arg->substr(1); } else if (*arg == "--restore") { op = opRestore; opName = arg->substr(1); } else if (*arg == "--export") { op = opExport; opName = arg->substr(1); } else if (*arg == "--import") { op = opImport; opName = arg->substr(1); } else if (*arg == "--init") op = opInit; else if (*arg == "--verify") { op = opVerify; opName = arg->substr(1); } else if (*arg == "--verify-path") { op = opVerifyPath; opName = arg->substr(1); } else if (*arg == "--repair-path") { op = opRepairPath; opName = arg->substr(1); } else if (*arg == "--optimise" || *arg == "--optimize") { op = opOptimise; opName = "-optimise"; } else if (*arg == "--serve") { op = opServe; opName = arg->substr(1); } else if (*arg == "--generate-binary-cache-key") { op = opGenerateBinaryCacheKey; opName = arg->substr(1); } else if (*arg == "--add-root") gcRoot = absPath(getArg(*arg, arg, end)); else if (*arg == "--stdin" && !isatty(STDIN_FILENO)) readFromStdIn = true; else if (*arg == "--indirect") ; else if (*arg == "--no-output") noOutput = true; else if (*arg != "" && arg->at(0) == '-') { opFlags.push_back(*arg); if (*arg == "--max-freed" || *arg == "--max-links" || *arg == "--max-atime") /* !!! hack */ opFlags.push_back(getArg(*arg, arg, end)); } else opArgs.push_back(*arg); if (readFromStdIn && op != opImport && op != opRestore && op != opServe) { std::string word; while (std::cin >> word) { opArgs.emplace_back(std::move(word)); }; } if (oldOp && oldOp != op) throw UsageError("only one operation may be specified"); return true; }); if (showHelp) showManPage("nix-store" + opName); if (!op) throw UsageError("no operation specified"); if (op != opDump && op != opRestore) /* !!! hack */ store = openStore(); op(std::move(opFlags), std::move(opArgs)); return 0; } } static RegisterLegacyCommand r_nix_store("nix-store", main_nix_store); }
41,387
C++
.cc
1,006
31.183897
147
0.569562
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
10,931
dotgraph.cc
NixOS_nix/src/nix-store/dotgraph.cc
#include "dotgraph.hh" #include "store-api.hh" #include <iostream> using std::cout; namespace nix { static std::string dotQuote(std::string_view s) { return "\"" + std::string(s) + "\""; } static const std::string & nextColour() { static int n = 0; static std::vector<std::string> colours { "black", "red", "green", "blue" , "magenta", "burlywood" }; return colours[n++ % colours.size()]; } static std::string makeEdge(std::string_view src, std::string_view dst) { return fmt("%1% -> %2% [color = %3%];\n", dotQuote(src), dotQuote(dst), dotQuote(nextColour())); } static std::string makeNode(std::string_view id, std::string_view label, std::string_view colour) { return fmt("%1% [label = %2%, shape = box, " "style = filled, fillcolor = %3%];\n", dotQuote(id), dotQuote(label), dotQuote(colour)); } void printDotGraph(ref<Store> store, StorePathSet && roots) { StorePathSet workList(std::move(roots)); StorePathSet doneSet; cout << "digraph G {\n"; while (!workList.empty()) { auto path = std::move(workList.extract(workList.begin()).value()); if (!doneSet.insert(path).second) continue; cout << makeNode(std::string(path.to_string()), path.name(), "#ff0000"); for (auto & p : store->queryPathInfo(path)->references) { if (p != path) { workList.insert(p); cout << makeEdge(std::string(p.to_string()), std::string(path.to_string())); } } } cout << "}\n"; } }
1,569
C++
.cc
48
27.3125
92
0.601734
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
10,932
pool.cc
NixOS_nix/src/libutil-tests/pool.cc
#include "pool.hh" #include <gtest/gtest.h> namespace nix { struct TestResource { TestResource() { static int counter = 0; num = counter++; } int dummyValue = 1; bool good = true; int num; }; /* ---------------------------------------------------------------------------- * Pool * --------------------------------------------------------------------------*/ TEST(Pool, freshPoolHasZeroCountAndSpecifiedCapacity) { auto isGood = [](const ref<TestResource> & r) { return r->good; }; auto createResource = []() { return make_ref<TestResource>(); }; Pool<TestResource> pool = Pool<TestResource>((size_t)1, createResource, isGood); ASSERT_EQ(pool.count(), 0); ASSERT_EQ(pool.capacity(), 1); } TEST(Pool, freshPoolCanGetAResource) { auto isGood = [](const ref<TestResource> & r) { return r->good; }; auto createResource = []() { return make_ref<TestResource>(); }; Pool<TestResource> pool = Pool<TestResource>((size_t)1, createResource, isGood); ASSERT_EQ(pool.count(), 0); TestResource r = *(pool.get()); ASSERT_EQ(pool.count(), 1); ASSERT_EQ(pool.capacity(), 1); ASSERT_EQ(r.dummyValue, 1); ASSERT_EQ(r.good, true); } TEST(Pool, capacityCanBeIncremented) { auto isGood = [](const ref<TestResource> & r) { return r->good; }; auto createResource = []() { return make_ref<TestResource>(); }; Pool<TestResource> pool = Pool<TestResource>((size_t)1, createResource, isGood); ASSERT_EQ(pool.capacity(), 1); pool.incCapacity(); ASSERT_EQ(pool.capacity(), 2); } TEST(Pool, capacityCanBeDecremented) { auto isGood = [](const ref<TestResource> & r) { return r->good; }; auto createResource = []() { return make_ref<TestResource>(); }; Pool<TestResource> pool = Pool<TestResource>((size_t)1, createResource, isGood); ASSERT_EQ(pool.capacity(), 1); pool.decCapacity(); ASSERT_EQ(pool.capacity(), 0); } TEST(Pool, flushBadDropsOutOfScopeResources) { auto isGood = [](const ref<TestResource> & r) { return false; }; auto createResource = []() { return make_ref<TestResource>(); }; Pool<TestResource> pool = Pool<TestResource>((size_t)1, createResource, isGood); { auto _r = pool.get(); ASSERT_EQ(pool.count(), 1); } pool.flushBad(); ASSERT_EQ(pool.count(), 0); } // Test that the resources we allocate are being reused when they are still good. TEST(Pool, reuseResource) { auto isGood = [](const ref<TestResource> & r) { return true; }; auto createResource = []() { return make_ref<TestResource>(); }; Pool<TestResource> pool = Pool<TestResource>((size_t)1, createResource, isGood); // Compare the instance counter between the two handles. We expect them to be equal // as the pool should hand out the same (still) good one again. int counter = -1; { Pool<TestResource>::Handle h = pool.get(); counter = h->num; } // the first handle goes out of scope { // the second handle should contain the same resource (with the same counter value) Pool<TestResource>::Handle h = pool.get(); ASSERT_EQ(h->num, counter); } } // Test that the resources we allocate are being thrown away when they are no longer good. TEST(Pool, badResourceIsNotReused) { auto isGood = [](const ref<TestResource> & r) { return false; }; auto createResource = []() { return make_ref<TestResource>(); }; Pool<TestResource> pool = Pool<TestResource>((size_t)1, createResource, isGood); // Compare the instance counter between the two handles. We expect them // to *not* be equal as the pool should hand out a new instance after // the first one was returned. int counter = -1; { Pool<TestResource>::Handle h = pool.get(); counter = h->num; } // the first handle goes out of scope { // the second handle should contain a different resource (with a //different counter value) Pool<TestResource>::Handle h = pool.get(); ASSERT_NE(h->num, counter); } } }
4,453
C++
.cc
99
36.363636
94
0.577901
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,933
checked-arithmetic.cc
NixOS_nix/src/libutil-tests/checked-arithmetic.cc
#include <cstdint> #include <gtest/gtest.h> #include <limits> #include <rapidcheck/Assertions.h> #include <rapidcheck/gtest.h> #include <rapidcheck/gen/Arbitrary.hpp> #include <checked-arithmetic.hh> #include "tests/gtest-with-params.hh" namespace rc { using namespace nix; template<std::integral T> struct Arbitrary<nix::checked::Checked<T>> { static Gen<nix::checked::Checked<T>> arbitrary() { return gen::arbitrary<T>(); } }; } namespace nix::checked { // Pointer to member function! Mildly gross. template<std::integral T> using Oper = Checked<T>::Result (Checked<T>::*)(T const other) const; template<std::integral T> using ReferenceOper = T (*)(T a, T b); /** * Checks that performing an operation that overflows into an inaccurate result * has the desired behaviour. * * TBig is a type large enough to represent all results of TSmall operations. */ template<std::integral TSmall, std::integral TBig> void checkType(TSmall a_, TSmall b, Oper<TSmall> oper, ReferenceOper<TBig> reference) { // Sufficient to fit all values TBig referenceResult = reference(a_, b); constexpr const TSmall minV = std::numeric_limits<TSmall>::min(); constexpr const TSmall maxV = std::numeric_limits<TSmall>::max(); Checked<TSmall> a{a_}; auto result = (a.*(oper))(b); // Just truncate it to get the in-range result RC_ASSERT(result.valueWrapping() == static_cast<TSmall>(referenceResult)); if (referenceResult > maxV || referenceResult < minV) { RC_ASSERT(result.overflowed()); RC_ASSERT(!result.valueChecked().has_value()); } else { RC_ASSERT(!result.overflowed()); RC_ASSERT(result.valueChecked().has_value()); RC_ASSERT(*result.valueChecked() == referenceResult); } } /** * Checks that performing an operation that overflows into an inaccurate result * has the desired behaviour. * * TBig is a type large enough to represent all results of TSmall operations. */ template<std::integral TSmall, std::integral TBig> void checkDivision(TSmall a_, TSmall b) { // Sufficient to fit all values constexpr const TSmall minV = std::numeric_limits<TSmall>::min(); Checked<TSmall> a{a_}; auto result = a / b; if (std::is_signed<TSmall>() && a_ == minV && b == -1) { // This is the only possible overflow condition RC_ASSERT(result.valueWrapping() == minV); RC_ASSERT(result.overflowed()); } else if (b == 0) { RC_ASSERT(result.divideByZero()); RC_ASSERT_THROWS_AS(result.valueWrapping(), nix::checked::DivideByZero); RC_ASSERT(result.valueChecked() == std::nullopt); } else { TBig referenceResult = a_ / b; auto result_ = result.valueChecked(); RC_ASSERT(result_.has_value()); RC_ASSERT(*result_ == referenceResult); RC_ASSERT(result.valueWrapping() == referenceResult); } } /** Creates parameters that perform a more adequate number of checks to validate * extremely cheap tests such as arithmetic tests */ static rc::detail::TestParams makeParams() { auto const & conf = rc::detail::configuration(); auto newParams = conf.testParams; newParams.maxSuccess = 10000; return newParams; } RC_GTEST_PROP_WITH_PARAMS(Checked, add_unsigned, makeParams, (uint16_t a, uint16_t b)) { checkType<uint16_t, int32_t>(a, b, &Checked<uint16_t>::operator+, [](int32_t a, int32_t b) { return a + b; }); } RC_GTEST_PROP_WITH_PARAMS(Checked, add_signed, makeParams, (int16_t a, int16_t b)) { checkType<int16_t, int32_t>(a, b, &Checked<int16_t>::operator+, [](int32_t a, int32_t b) { return a + b; }); } RC_GTEST_PROP_WITH_PARAMS(Checked, sub_unsigned, makeParams, (uint16_t a, uint16_t b)) { checkType<uint16_t, int32_t>(a, b, &Checked<uint16_t>::operator-, [](int32_t a, int32_t b) { return a - b; }); } RC_GTEST_PROP_WITH_PARAMS(Checked, sub_signed, makeParams, (int16_t a, int16_t b)) { checkType<int16_t, int32_t>(a, b, &Checked<int16_t>::operator-, [](int32_t a, int32_t b) { return a - b; }); } RC_GTEST_PROP_WITH_PARAMS(Checked, mul_unsigned, makeParams, (uint16_t a, uint16_t b)) { checkType<uint16_t, int64_t>(a, b, &Checked<uint16_t>::operator*, [](int64_t a, int64_t b) { return a * b; }); } RC_GTEST_PROP_WITH_PARAMS(Checked, mul_signed, makeParams, (int16_t a, int16_t b)) { checkType<int16_t, int64_t>(a, b, &Checked<int16_t>::operator*, [](int64_t a, int64_t b) { return a * b; }); } RC_GTEST_PROP_WITH_PARAMS(Checked, div_unsigned, makeParams, (uint16_t a, uint16_t b)) { checkDivision<uint16_t, int64_t>(a, b); } RC_GTEST_PROP_WITH_PARAMS(Checked, div_signed, makeParams, (int16_t a, int16_t b)) { checkDivision<int16_t, int64_t>(a, b); } // Make absolutely sure that we check the special cases if the proptest // generator does not come up with them. This one is especially important // because it has very specific pairs required for the edge cases unlike the // others. TEST(Checked, div_signed_special_cases) { checkDivision<int16_t, int64_t>(std::numeric_limits<int16_t>::min(), -1); checkDivision<int16_t, int64_t>(std::numeric_limits<int16_t>::min(), 0); checkDivision<int16_t, int64_t>(0, 0); } }
5,200
C++
.cc
132
35.962121
114
0.688219
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,934
url.cc
NixOS_nix/src/libutil-tests/url.cc
#include "url.hh" #include <gtest/gtest.h> namespace nix { /* ----------- tests for url.hh --------------------------------------------------*/ std::string print_map(std::map<std::string, std::string> m) { std::map<std::string, std::string>::iterator it; std::string s = "{ "; for (it = m.begin(); it != m.end(); ++it) { s += "{ "; s += it->first; s += " = "; s += it->second; s += " } "; } s += "}"; return s; } std::ostream& operator<<(std::ostream& os, const ParsedURL& p) { return os << "\n" << "url: " << p.url << "\n" << "base: " << p.base << "\n" << "scheme: " << p.scheme << "\n" << "authority: " << p.authority.value() << "\n" << "path: " << p.path << "\n" << "query: " << print_map(p.query) << "\n" << "fragment: " << p.fragment << "\n"; } TEST(parseURL, parsesSimpleHttpUrl) { auto s = "http://www.example.org/file.tar.gz"; auto parsed = parseURL(s); ParsedURL expected { .url = "http://www.example.org/file.tar.gz", .base = "http://www.example.org/file.tar.gz", .scheme = "http", .authority = "www.example.org", .path = "/file.tar.gz", .query = (StringMap) { }, .fragment = "", }; ASSERT_EQ(parsed, expected); } TEST(parseURL, parsesSimpleHttpsUrl) { auto s = "https://www.example.org/file.tar.gz"; auto parsed = parseURL(s); ParsedURL expected { .url = "https://www.example.org/file.tar.gz", .base = "https://www.example.org/file.tar.gz", .scheme = "https", .authority = "www.example.org", .path = "/file.tar.gz", .query = (StringMap) { }, .fragment = "", }; ASSERT_EQ(parsed, expected); } TEST(parseURL, parsesSimpleHttpUrlWithQueryAndFragment) { auto s = "https://www.example.org/file.tar.gz?download=fast&when=now#hello"; auto parsed = parseURL(s); ParsedURL expected { .url = "https://www.example.org/file.tar.gz", .base = "https://www.example.org/file.tar.gz", .scheme = "https", .authority = "www.example.org", .path = "/file.tar.gz", .query = (StringMap) { { "download", "fast" }, { "when", "now" } }, .fragment = "hello", }; ASSERT_EQ(parsed, expected); } TEST(parseURL, parsesSimpleHttpUrlWithComplexFragment) { auto s = "http://www.example.org/file.tar.gz?field=value#?foo=bar%23"; auto parsed = parseURL(s); ParsedURL expected { .url = "http://www.example.org/file.tar.gz", .base = "http://www.example.org/file.tar.gz", .scheme = "http", .authority = "www.example.org", .path = "/file.tar.gz", .query = (StringMap) { { "field", "value" } }, .fragment = "?foo=bar#", }; ASSERT_EQ(parsed, expected); } TEST(parseURL, parsesFilePlusHttpsUrl) { auto s = "file+https://www.example.org/video.mp4"; auto parsed = parseURL(s); ParsedURL expected { .url = "file+https://www.example.org/video.mp4", .base = "https://www.example.org/video.mp4", .scheme = "file+https", .authority = "www.example.org", .path = "/video.mp4", .query = (StringMap) { }, .fragment = "", }; ASSERT_EQ(parsed, expected); } TEST(parseURL, rejectsAuthorityInUrlsWithFileTransportation) { auto s = "file://www.example.org/video.mp4"; ASSERT_THROW(parseURL(s), Error); } TEST(parseURL, parseIPv4Address) { auto s = "http://127.0.0.1:8080/file.tar.gz?download=fast&when=now#hello"; auto parsed = parseURL(s); ParsedURL expected { .url = "http://127.0.0.1:8080/file.tar.gz", .base = "https://127.0.0.1:8080/file.tar.gz", .scheme = "http", .authority = "127.0.0.1:8080", .path = "/file.tar.gz", .query = (StringMap) { { "download", "fast" }, { "when", "now" } }, .fragment = "hello", }; ASSERT_EQ(parsed, expected); } TEST(parseURL, parseScopedRFC4007IPv6Address) { auto s = "http://[fe80::818c:da4d:8975:415c\%enp0s25]:8080"; auto parsed = parseURL(s); ParsedURL expected { .url = "http://[fe80::818c:da4d:8975:415c\%enp0s25]:8080", .base = "http://[fe80::818c:da4d:8975:415c\%enp0s25]:8080", .scheme = "http", .authority = "[fe80::818c:da4d:8975:415c\%enp0s25]:8080", .path = "", .query = (StringMap) { }, .fragment = "", }; ASSERT_EQ(parsed, expected); } TEST(parseURL, parseIPv6Address) { auto s = "http://[2a02:8071:8192:c100:311d:192d:81ac:11ea]:8080"; auto parsed = parseURL(s); ParsedURL expected { .url = "http://[2a02:8071:8192:c100:311d:192d:81ac:11ea]:8080", .base = "http://[2a02:8071:8192:c100:311d:192d:81ac:11ea]:8080", .scheme = "http", .authority = "[2a02:8071:8192:c100:311d:192d:81ac:11ea]:8080", .path = "", .query = (StringMap) { }, .fragment = "", }; ASSERT_EQ(parsed, expected); } TEST(parseURL, parseEmptyQueryParams) { auto s = "http://127.0.0.1:8080/file.tar.gz?&&&&&"; auto parsed = parseURL(s); ASSERT_EQ(parsed.query, (StringMap) { }); } TEST(parseURL, parseUserPassword) { auto s = "http://user:pass@www.example.org:8080/file.tar.gz"; auto parsed = parseURL(s); ParsedURL expected { .url = "http://user:pass@www.example.org/file.tar.gz", .base = "http://user:pass@www.example.org/file.tar.gz", .scheme = "http", .authority = "user:pass@www.example.org:8080", .path = "/file.tar.gz", .query = (StringMap) { }, .fragment = "", }; ASSERT_EQ(parsed, expected); } TEST(parseURL, parseFileURLWithQueryAndFragment) { auto s = "file:///none/of//your/business"; auto parsed = parseURL(s); ParsedURL expected { .url = "", .base = "", .scheme = "file", .authority = "", .path = "/none/of//your/business", .query = (StringMap) { }, .fragment = "", }; ASSERT_EQ(parsed, expected); } TEST(parseURL, parsedUrlsIsEqualToItself) { auto s = "http://www.example.org/file.tar.gz"; auto url = parseURL(s); ASSERT_TRUE(url == url); } TEST(parseURL, parseFTPUrl) { auto s = "ftp://ftp.nixos.org/downloads/nixos.iso"; auto parsed = parseURL(s); ParsedURL expected { .url = "ftp://ftp.nixos.org/downloads/nixos.iso", .base = "ftp://ftp.nixos.org/downloads/nixos.iso", .scheme = "ftp", .authority = "ftp.nixos.org", .path = "/downloads/nixos.iso", .query = (StringMap) { }, .fragment = "", }; ASSERT_EQ(parsed, expected); } TEST(parseURL, parsesAnythingInUriFormat) { auto s = "whatever://github.com/NixOS/nixpkgs.git"; auto parsed = parseURL(s); } TEST(parseURL, parsesAnythingInUriFormatWithoutDoubleSlash) { auto s = "whatever:github.com/NixOS/nixpkgs.git"; auto parsed = parseURL(s); } TEST(parseURL, emptyStringIsInvalidURL) { ASSERT_THROW(parseURL(""), Error); } /* ---------------------------------------------------------------------------- * decodeQuery * --------------------------------------------------------------------------*/ TEST(decodeQuery, emptyStringYieldsEmptyMap) { auto d = decodeQuery(""); ASSERT_EQ(d, (StringMap) { }); } TEST(decodeQuery, simpleDecode) { auto d = decodeQuery("yi=one&er=two"); ASSERT_EQ(d, ((StringMap) { { "yi", "one" }, { "er", "two" } })); } TEST(decodeQuery, decodeUrlEncodedArgs) { auto d = decodeQuery("arg=%3D%3D%40%3D%3D"); ASSERT_EQ(d, ((StringMap) { { "arg", "==@==" } })); } TEST(decodeQuery, decodeArgWithEmptyValue) { auto d = decodeQuery("arg="); ASSERT_EQ(d, ((StringMap) { { "arg", ""} })); } /* ---------------------------------------------------------------------------- * percentDecode * --------------------------------------------------------------------------*/ TEST(percentDecode, decodesUrlEncodedString) { std::string s = "==@=="; std::string d = percentDecode("%3D%3D%40%3D%3D"); ASSERT_EQ(d, s); } TEST(percentDecode, multipleDecodesAreIdempotent) { std::string once = percentDecode("%3D%3D%40%3D%3D"); std::string twice = percentDecode(once); ASSERT_EQ(once, twice); } TEST(percentDecode, trailingPercent) { std::string s = "==@==%"; std::string d = percentDecode("%3D%3D%40%3D%3D%25"); ASSERT_EQ(d, s); } /* ---------------------------------------------------------------------------- * percentEncode * --------------------------------------------------------------------------*/ TEST(percentEncode, encodesUrlEncodedString) { std::string s = percentEncode("==@=="); std::string d = "%3D%3D%40%3D%3D"; ASSERT_EQ(d, s); } TEST(percentEncode, keepArgument) { std::string a = percentEncode("abd / def"); std::string b = percentEncode("abd / def", "/"); ASSERT_EQ(a, "abd%20%2F%20def"); ASSERT_EQ(b, "abd%20/%20def"); } TEST(percentEncode, inverseOfDecode) { std::string original = "%3D%3D%40%3D%3D"; std::string once = percentEncode(original); std::string back = percentDecode(once); ASSERT_EQ(back, original); } TEST(percentEncode, trailingPercent) { std::string s = percentEncode("==@==%"); std::string d = "%3D%3D%40%3D%3D%25"; ASSERT_EQ(d, s); } TEST(percentEncode, yen) { // https://en.wikipedia.org/wiki/Percent-encoding#Character_data std::string s = reinterpret_cast<const char*>(u8"円"); std::string e = "%E5%86%86"; ASSERT_EQ(percentEncode(s), e); ASSERT_EQ(percentDecode(e), s); } TEST(nix, isValidSchemeName) { ASSERT_TRUE(isValidSchemeName("http")); ASSERT_TRUE(isValidSchemeName("https")); ASSERT_TRUE(isValidSchemeName("file")); ASSERT_TRUE(isValidSchemeName("file+https")); ASSERT_TRUE(isValidSchemeName("fi.le")); ASSERT_TRUE(isValidSchemeName("file-ssh")); ASSERT_TRUE(isValidSchemeName("file+")); ASSERT_TRUE(isValidSchemeName("file.")); ASSERT_TRUE(isValidSchemeName("file1")); ASSERT_FALSE(isValidSchemeName("file:")); ASSERT_FALSE(isValidSchemeName("file/")); ASSERT_FALSE(isValidSchemeName("+file")); ASSERT_FALSE(isValidSchemeName(".file")); ASSERT_FALSE(isValidSchemeName("-file")); ASSERT_FALSE(isValidSchemeName("1file")); // regex ok? ASSERT_FALSE(isValidSchemeName("\nhttp")); ASSERT_FALSE(isValidSchemeName("\nhttp\n")); ASSERT_FALSE(isValidSchemeName("http\n")); ASSERT_FALSE(isValidSchemeName("http ")); } }
11,762
C++
.cc
298
30.281879
84
0.513079
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,935
chunked-vector.cc
NixOS_nix/src/libutil-tests/chunked-vector.cc
#include "chunked-vector.hh" #include <gtest/gtest.h> namespace nix { TEST(ChunkedVector, InitEmpty) { auto v = ChunkedVector<int, 2>(100); ASSERT_EQ(v.size(), 0); } TEST(ChunkedVector, GrowsCorrectly) { auto v = ChunkedVector<int, 2>(100); for (auto i = 1; i < 20; i++) { v.add(i); ASSERT_EQ(v.size(), i); } } TEST(ChunkedVector, AddAndGet) { auto v = ChunkedVector<int, 2>(100); for (auto i = 1; i < 20; i++) { auto [i2, idx] = v.add(i); auto & i3 = v[idx]; ASSERT_EQ(i, i2); ASSERT_EQ(&i2, &i3); } } TEST(ChunkedVector, ForEach) { auto v = ChunkedVector<int, 2>(100); for (auto i = 1; i < 20; i++) { v.add(i); } int count = 0; v.forEach([&count](int elt) { count++; }); ASSERT_EQ(count, v.size()); } TEST(ChunkedVector, OverflowOK) { // Similar to the AddAndGet, but intentionnally use a small // initial ChunkedVector to force it to overflow auto v = ChunkedVector<int, 2>(2); for (auto i = 1; i < 20; i++) { auto [i2, idx] = v.add(i); auto & i3 = v[idx]; ASSERT_EQ(i, i2); ASSERT_EQ(&i2, &i3); } } }
1,357
C++
.cc
46
20.847826
67
0.4835
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,936
processes.cc
NixOS_nix/src/libutil-tests/processes.cc
#include "processes.hh" #include <gtest/gtest.h> namespace nix { /* ---------------------------------------------------------------------------- * statusOk * --------------------------------------------------------------------------*/ TEST(statusOk, zeroIsOk) { ASSERT_EQ(statusOk(0), true); ASSERT_EQ(statusOk(1), false); } } // namespace nix
359
C++
.cc
12
27.666667
79
0.383041
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,937
executable-path.cc
NixOS_nix/src/libutil-tests/executable-path.cc
#include <gtest/gtest.h> #include "executable-path.hh" namespace nix { #ifdef WIN32 # define PATH_VAR_SEP L";" #else # define PATH_VAR_SEP ":" #endif #define PATH_ENV_ROUND_TRIP(NAME, STRING_LIT, CXX_LIT) \ TEST(ExecutablePath, NAME) \ { \ OsString s = STRING_LIT; \ auto v = ExecutablePath::parse(s); \ EXPECT_EQ(v, (ExecutablePath CXX_LIT)); \ auto s2 = v.render(); \ EXPECT_EQ(s2, s); \ } PATH_ENV_ROUND_TRIP(emptyRoundTrip, OS_STR(""), ({})) PATH_ENV_ROUND_TRIP( oneElemRoundTrip, OS_STR("/foo"), ({ OS_STR("/foo"), })) PATH_ENV_ROUND_TRIP( twoElemsRoundTrip, OS_STR("/foo" PATH_VAR_SEP "/bar"), ({ OS_STR("/foo"), OS_STR("/bar"), })) PATH_ENV_ROUND_TRIP( threeElemsRoundTrip, OS_STR("/foo" PATH_VAR_SEP "." PATH_VAR_SEP "/bar"), ({ OS_STR("/foo"), OS_STR("."), OS_STR("/bar"), })) TEST(ExecutablePath, elementyElemNormalize) { auto v = ExecutablePath::parse(PATH_VAR_SEP PATH_VAR_SEP PATH_VAR_SEP); EXPECT_EQ( v, (ExecutablePath{{ OS_STR("."), OS_STR("."), OS_STR("."), OS_STR("."), }})); auto s2 = v.render(); EXPECT_EQ(s2, OS_STR("." PATH_VAR_SEP "." PATH_VAR_SEP "." PATH_VAR_SEP ".")); } }
1,515
C++
.cc
54
22.5
82
0.481048
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,938
config.cc
NixOS_nix/src/libutil-tests/config.cc
#include "config.hh" #include "args.hh" #include <sstream> #include <gtest/gtest.h> #include <nlohmann/json.hpp> namespace nix { /* ---------------------------------------------------------------------------- * Config * --------------------------------------------------------------------------*/ TEST(Config, setUndefinedSetting) { Config config; ASSERT_EQ(config.set("undefined-key", "value"), false); } TEST(Config, setDefinedSetting) { Config config; std::string value; Setting<std::string> foo{&config, value, "name-of-the-setting", "description"}; ASSERT_EQ(config.set("name-of-the-setting", "value"), true); } TEST(Config, getDefinedSetting) { Config config; std::string value; std::map<std::string, Config::SettingInfo> settings; Setting<std::string> foo{&config, value, "name-of-the-setting", "description"}; config.getSettings(settings, /* overriddenOnly = */ false); const auto iter = settings.find("name-of-the-setting"); ASSERT_NE(iter, settings.end()); ASSERT_EQ(iter->second.value, ""); ASSERT_EQ(iter->second.description, "description\n"); } TEST(Config, getDefinedOverriddenSettingNotSet) { Config config; std::string value; std::map<std::string, Config::SettingInfo> settings; Setting<std::string> foo{&config, value, "name-of-the-setting", "description"}; config.getSettings(settings, /* overriddenOnly = */ true); const auto e = settings.find("name-of-the-setting"); ASSERT_EQ(e, settings.end()); } TEST(Config, getDefinedSettingSet1) { Config config; std::string value; std::map<std::string, Config::SettingInfo> settings; Setting<std::string> setting{&config, value, "name-of-the-setting", "description"}; setting.assign("value"); config.getSettings(settings, /* overriddenOnly = */ false); const auto iter = settings.find("name-of-the-setting"); ASSERT_NE(iter, settings.end()); ASSERT_EQ(iter->second.value, "value"); ASSERT_EQ(iter->second.description, "description\n"); } TEST(Config, getDefinedSettingSet2) { Config config; std::map<std::string, Config::SettingInfo> settings; Setting<std::string> setting{&config, "", "name-of-the-setting", "description"}; ASSERT_TRUE(config.set("name-of-the-setting", "value")); config.getSettings(settings, /* overriddenOnly = */ false); const auto e = settings.find("name-of-the-setting"); ASSERT_NE(e, settings.end()); ASSERT_EQ(e->second.value, "value"); ASSERT_EQ(e->second.description, "description\n"); } TEST(Config, addSetting) { class TestSetting : public AbstractSetting { public: TestSetting() : AbstractSetting("test", "test", {}) {} void set(const std::string & value, bool append) override {} std::string to_string() const override { return {}; } bool isAppendable() override { return false; } }; Config config; TestSetting setting; ASSERT_FALSE(config.set("test", "value")); config.addSetting(&setting); ASSERT_TRUE(config.set("test", "value")); ASSERT_FALSE(config.set("extra-test", "value")); } TEST(Config, withInitialValue) { const StringMap initials = { { "key", "value" }, }; Config config(initials); { std::map<std::string, Config::SettingInfo> settings; config.getSettings(settings, /* overriddenOnly = */ false); ASSERT_EQ(settings.find("key"), settings.end()); } Setting<std::string> setting{&config, "default-value", "key", "description"}; { std::map<std::string, Config::SettingInfo> settings; config.getSettings(settings, /* overriddenOnly = */ false); ASSERT_EQ(settings["key"].value, "value"); } } TEST(Config, resetOverridden) { Config config; config.resetOverridden(); } TEST(Config, resetOverriddenWithSetting) { Config config; Setting<std::string> setting{&config, "", "name-of-the-setting", "description"}; { std::map<std::string, Config::SettingInfo> settings; setting.set("foo"); ASSERT_EQ(setting.get(), "foo"); config.getSettings(settings, /* overriddenOnly = */ true); ASSERT_TRUE(settings.empty()); } { std::map<std::string, Config::SettingInfo> settings; setting.override("bar"); ASSERT_TRUE(setting.overridden); ASSERT_EQ(setting.get(), "bar"); config.getSettings(settings, /* overriddenOnly = */ true); ASSERT_FALSE(settings.empty()); } { std::map<std::string, Config::SettingInfo> settings; config.resetOverridden(); ASSERT_FALSE(setting.overridden); config.getSettings(settings, /* overriddenOnly = */ true); ASSERT_TRUE(settings.empty()); } } TEST(Config, toJSONOnEmptyConfig) { ASSERT_EQ(Config().toJSON().dump(), "{}"); } TEST(Config, toJSONOnNonEmptyConfig) { using nlohmann::literals::operator "" _json; Config config; Setting<std::string> setting{ &config, "", "name-of-the-setting", "description", }; setting.assign("value"); ASSERT_EQ(config.toJSON(), R"#({ "name-of-the-setting": { "aliases": [], "defaultValue": "", "description": "description\n", "documentDefault": true, "value": "value", "experimentalFeature": null } })#"_json); } TEST(Config, toJSONOnNonEmptyConfigWithExperimentalSetting) { using nlohmann::literals::operator "" _json; Config config; Setting<std::string> setting{ &config, "", "name-of-the-setting", "description", {}, true, Xp::Flakes, }; setting.assign("value"); ASSERT_EQ(config.toJSON(), R"#({ "name-of-the-setting": { "aliases": [], "defaultValue": "", "description": "description\n", "documentDefault": true, "value": "value", "experimentalFeature": "flakes" } })#"_json); } TEST(Config, setSettingAlias) { Config config; Setting<std::string> setting{&config, "", "some-int", "best number", { "another-int" }}; ASSERT_TRUE(config.set("some-int", "1")); ASSERT_EQ(setting.get(), "1"); ASSERT_TRUE(config.set("another-int", "2")); ASSERT_EQ(setting.get(), "2"); ASSERT_TRUE(config.set("some-int", "3")); ASSERT_EQ(setting.get(), "3"); } /* FIXME: The reapplyUnknownSettings method doesn't seem to do anything * useful (these days). Whenever we add a new setting to Config the * unknown settings are always considered. In which case is this function * actually useful? Is there some way to register a Setting without calling * addSetting? */ TEST(Config, DISABLED_reapplyUnknownSettings) { Config config; ASSERT_FALSE(config.set("name-of-the-setting", "unknownvalue")); Setting<std::string> setting{&config, "default", "name-of-the-setting", "description"}; ASSERT_EQ(setting.get(), "default"); config.reapplyUnknownSettings(); ASSERT_EQ(setting.get(), "unknownvalue"); } TEST(Config, applyConfigEmpty) { Config config; std::map<std::string, Config::SettingInfo> settings; config.applyConfig(""); config.getSettings(settings); ASSERT_TRUE(settings.empty()); } TEST(Config, applyConfigEmptyWithComment) { Config config; std::map<std::string, Config::SettingInfo> settings; config.applyConfig("# just a comment"); config.getSettings(settings); ASSERT_TRUE(settings.empty()); } TEST(Config, applyConfigAssignment) { Config config; std::map<std::string, Config::SettingInfo> settings; Setting<std::string> setting{&config, "", "name-of-the-setting", "description"}; config.applyConfig( "name-of-the-setting = value-from-file #useful comment\n" "# name-of-the-setting = foo\n" ); config.getSettings(settings); ASSERT_FALSE(settings.empty()); ASSERT_EQ(settings["name-of-the-setting"].value, "value-from-file"); } TEST(Config, applyConfigWithReassignedSetting) { Config config; std::map<std::string, Config::SettingInfo> settings; Setting<std::string> setting{&config, "", "name-of-the-setting", "description"}; config.applyConfig( "name-of-the-setting = first-value\n" "name-of-the-setting = second-value\n" ); config.getSettings(settings); ASSERT_FALSE(settings.empty()); ASSERT_EQ(settings["name-of-the-setting"].value, "second-value"); } TEST(Config, applyConfigFailsOnMissingIncludes) { Config config; std::map<std::string, Config::SettingInfo> settings; Setting<std::string> setting{&config, "", "name-of-the-setting", "description"}; ASSERT_THROW(config.applyConfig( "name-of-the-setting = value-from-file\n" "# name-of-the-setting = foo\n" "include /nix/store/does/not/exist.nix" ), Error); } TEST(Config, applyConfigInvalidThrows) { Config config; ASSERT_THROW(config.applyConfig("value == key"), UsageError); ASSERT_THROW(config.applyConfig("value "), UsageError); } }
10,103
C++
.cc
251
30.956175
96
0.580139
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
10,939
closure.cc
NixOS_nix/src/libutil-tests/closure.cc
#include "closure.hh" #include <gtest/gtest.h> namespace nix { using namespace std; map<string, set<string>> testGraph = { { "A", { "B", "C", "G" } }, { "B", { "A" } }, // Loops back to A { "C", { "F" } }, // Indirect reference { "D", { "A" } }, // Not reachable, but has backreferences { "E", {} }, // Just not reachable { "F", {} }, { "G", { "G" } }, // Self reference }; TEST(closure, correctClosure) { set<string> aClosure; set<string> expectedClosure = {"A", "B", "C", "F", "G"}; computeClosure<string>( {"A"}, aClosure, [&](const string currentNode, function<void(promise<set<string>> &)> processEdges) { promise<set<string>> promisedNodes; promisedNodes.set_value(testGraph[currentNode]); processEdges(promisedNodes); } ); ASSERT_EQ(aClosure, expectedClosure); } TEST(closure, properlyHandlesDirectExceptions) { struct TestExn {}; set<string> aClosure; EXPECT_THROW( computeClosure<string>( {"A"}, aClosure, [&](const string currentNode, function<void(promise<set<string>> &)> processEdges) { throw TestExn(); } ), TestExn ); } TEST(closure, properlyHandlesExceptionsInPromise) { struct TestExn {}; set<string> aClosure; EXPECT_THROW( computeClosure<string>( {"A"}, aClosure, [&](const string currentNode, function<void(promise<set<string>> &)> processEdges) { promise<set<string>> promise; try { throw TestExn(); } catch (...) { promise.set_exception(std::current_exception()); } processEdges(promise); } ), TestExn ); } }
1,867
C++
.cc
62
22.080645
96
0.533667
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,940
util.cc
NixOS_nix/src/libutil-tests/util.cc
#include "util.hh" #include "types.hh" #include "file-system.hh" #include "terminal.hh" #include "strings.hh" #include <limits.h> #include <gtest/gtest.h> #include <numeric> namespace nix { /* ----------- tests for util.hh --------------------------------------------*/ /* ---------------------------------------------------------------------------- * hasPrefix * --------------------------------------------------------------------------*/ TEST(hasPrefix, emptyStringHasNoPrefix) { ASSERT_FALSE(hasPrefix("", "foo")); } TEST(hasPrefix, emptyStringIsAlwaysPrefix) { ASSERT_TRUE(hasPrefix("foo", "")); ASSERT_TRUE(hasPrefix("jshjkfhsadf", "")); } TEST(hasPrefix, trivialCase) { ASSERT_TRUE(hasPrefix("foobar", "foo")); } /* ---------------------------------------------------------------------------- * hasSuffix * --------------------------------------------------------------------------*/ TEST(hasSuffix, emptyStringHasNoSuffix) { ASSERT_FALSE(hasSuffix("", "foo")); } TEST(hasSuffix, trivialCase) { ASSERT_TRUE(hasSuffix("foo", "foo")); ASSERT_TRUE(hasSuffix("foobar", "bar")); } /* ---------------------------------------------------------------------------- * base64Encode * --------------------------------------------------------------------------*/ TEST(base64Encode, emptyString) { ASSERT_EQ(base64Encode(""), ""); } TEST(base64Encode, encodesAString) { ASSERT_EQ(base64Encode("quod erat demonstrandum"), "cXVvZCBlcmF0IGRlbW9uc3RyYW5kdW0="); } TEST(base64Encode, encodeAndDecode) { auto s = "quod erat demonstrandum"; auto encoded = base64Encode(s); auto decoded = base64Decode(encoded); ASSERT_EQ(decoded, s); } TEST(base64Encode, encodeAndDecodeNonPrintable) { char s[256]; std::iota(std::rbegin(s), std::rend(s), 0); auto encoded = base64Encode(s); auto decoded = base64Decode(encoded); EXPECT_EQ(decoded.length(), 255); ASSERT_EQ(decoded, s); } /* ---------------------------------------------------------------------------- * base64Decode * --------------------------------------------------------------------------*/ TEST(base64Decode, emptyString) { ASSERT_EQ(base64Decode(""), ""); } TEST(base64Decode, decodeAString) { ASSERT_EQ(base64Decode("cXVvZCBlcmF0IGRlbW9uc3RyYW5kdW0="), "quod erat demonstrandum"); } TEST(base64Decode, decodeThrowsOnInvalidChar) { ASSERT_THROW(base64Decode("cXVvZCBlcm_0IGRlbW9uc3RyYW5kdW0="), Error); } /* ---------------------------------------------------------------------------- * getLine * --------------------------------------------------------------------------*/ TEST(getLine, all) { { auto [line, rest] = getLine("foo\nbar\nxyzzy"); ASSERT_EQ(line, "foo"); ASSERT_EQ(rest, "bar\nxyzzy"); } { auto [line, rest] = getLine("foo\r\nbar\r\nxyzzy"); ASSERT_EQ(line, "foo"); ASSERT_EQ(rest, "bar\r\nxyzzy"); } { auto [line, rest] = getLine("foo\n"); ASSERT_EQ(line, "foo"); ASSERT_EQ(rest, ""); } { auto [line, rest] = getLine("foo"); ASSERT_EQ(line, "foo"); ASSERT_EQ(rest, ""); } { auto [line, rest] = getLine(""); ASSERT_EQ(line, ""); ASSERT_EQ(rest, ""); } } /* ---------------------------------------------------------------------------- * toLower * --------------------------------------------------------------------------*/ TEST(toLower, emptyString) { ASSERT_EQ(toLower(""), ""); } TEST(toLower, nonLetters) { auto s = "!@(*$#)(@#=\\234_"; ASSERT_EQ(toLower(s), s); } // std::tolower() doesn't handle unicode characters. In the context of // store paths this isn't relevant but doesn't hurt to record this behavior // here. TEST(toLower, umlauts) { auto s = "ÄÖÜ"; ASSERT_EQ(toLower(s), "ÄÖÜ"); } /* ---------------------------------------------------------------------------- * string2Float * --------------------------------------------------------------------------*/ TEST(string2Float, emptyString) { ASSERT_EQ(string2Float<double>(""), std::nullopt); } TEST(string2Float, trivialConversions) { ASSERT_EQ(string2Float<double>("1.0"), 1.0); ASSERT_EQ(string2Float<double>("0.0"), 0.0); ASSERT_EQ(string2Float<double>("-100.25"), -100.25); } /* ---------------------------------------------------------------------------- * string2Int * --------------------------------------------------------------------------*/ TEST(string2Int, emptyString) { ASSERT_EQ(string2Int<int>(""), std::nullopt); } TEST(string2Int, trivialConversions) { ASSERT_EQ(string2Int<int>("1"), 1); ASSERT_EQ(string2Int<int>("0"), 0); ASSERT_EQ(string2Int<int>("-100"), -100); } /* ---------------------------------------------------------------------------- * renderSize * --------------------------------------------------------------------------*/ TEST(renderSize, misc) { ASSERT_EQ(renderSize(0, true), " 0.0 KiB"); ASSERT_EQ(renderSize(100, true), " 0.1 KiB"); ASSERT_EQ(renderSize(100), "0.1 KiB"); ASSERT_EQ(renderSize(972, true), " 0.9 KiB"); ASSERT_EQ(renderSize(973, true), " 1.0 KiB"); // FIXME: should round down ASSERT_EQ(renderSize(1024, true), " 1.0 KiB"); ASSERT_EQ(renderSize(1024 * 1024, true), "1024.0 KiB"); ASSERT_EQ(renderSize(1100 * 1024, true), " 1.1 MiB"); ASSERT_EQ(renderSize(2ULL * 1024 * 1024 * 1024, true), " 2.0 GiB"); ASSERT_EQ(renderSize(2100ULL * 1024 * 1024 * 1024, true), " 2.1 TiB"); } /* ---------------------------------------------------------------------------- * rewriteStrings * --------------------------------------------------------------------------*/ TEST(rewriteStrings, emptyString) { StringMap rewrites; rewrites["this"] = "that"; ASSERT_EQ(rewriteStrings("", rewrites), ""); } TEST(rewriteStrings, emptyRewrites) { StringMap rewrites; ASSERT_EQ(rewriteStrings("this and that", rewrites), "this and that"); } TEST(rewriteStrings, successfulRewrite) { StringMap rewrites; rewrites["this"] = "that"; ASSERT_EQ(rewriteStrings("this and that", rewrites), "that and that"); } TEST(rewriteStrings, doesntOccur) { StringMap rewrites; rewrites["foo"] = "bar"; ASSERT_EQ(rewriteStrings("this and that", rewrites), "this and that"); } /* ---------------------------------------------------------------------------- * replaceStrings * --------------------------------------------------------------------------*/ TEST(replaceStrings, emptyString) { ASSERT_EQ(replaceStrings("", "this", "that"), ""); ASSERT_EQ(replaceStrings("this and that", "", ""), "this and that"); } TEST(replaceStrings, successfulReplace) { ASSERT_EQ(replaceStrings("this and that", "this", "that"), "that and that"); } TEST(replaceStrings, doesntOccur) { ASSERT_EQ(replaceStrings("this and that", "foo", "bar"), "this and that"); } /* ---------------------------------------------------------------------------- * trim * --------------------------------------------------------------------------*/ TEST(trim, emptyString) { ASSERT_EQ(trim(""), ""); } TEST(trim, removesWhitespace) { ASSERT_EQ(trim("foo"), "foo"); ASSERT_EQ(trim(" foo "), "foo"); ASSERT_EQ(trim(" foo bar baz"), "foo bar baz"); ASSERT_EQ(trim(" \t foo bar baz\n"), "foo bar baz"); } /* ---------------------------------------------------------------------------- * chomp * --------------------------------------------------------------------------*/ TEST(chomp, emptyString) { ASSERT_EQ(chomp(""), ""); } TEST(chomp, removesWhitespace) { ASSERT_EQ(chomp("foo"), "foo"); ASSERT_EQ(chomp("foo "), "foo"); ASSERT_EQ(chomp(" foo "), " foo"); ASSERT_EQ(chomp(" foo bar baz "), " foo bar baz"); ASSERT_EQ(chomp("\t foo bar baz\n"), "\t foo bar baz"); } /* ---------------------------------------------------------------------------- * quoteStrings * --------------------------------------------------------------------------*/ TEST(quoteStrings, empty) { Strings s = {}; Strings expected = {}; ASSERT_EQ(quoteStrings(s), expected); } TEST(quoteStrings, emptyStrings) { Strings s = {"", "", ""}; Strings expected = {"''", "''", "''"}; ASSERT_EQ(quoteStrings(s), expected); } TEST(quoteStrings, trivialQuote) { Strings s = {"foo", "bar", "baz"}; Strings expected = {"'foo'", "'bar'", "'baz'"}; ASSERT_EQ(quoteStrings(s), expected); } TEST(quoteStrings, quotedStrings) { Strings s = {"'foo'", "'bar'", "'baz'"}; Strings expected = {"''foo''", "''bar''", "''baz''"}; ASSERT_EQ(quoteStrings(s), expected); } /* ---------------------------------------------------------------------------- * get * --------------------------------------------------------------------------*/ TEST(get, emptyContainer) { StringMap s = {}; auto expected = nullptr; ASSERT_EQ(get(s, "one"), expected); } TEST(get, getFromContainer) { StringMap s; s["one"] = "yi"; s["two"] = "er"; auto expected = "yi"; ASSERT_EQ(*get(s, "one"), expected); } TEST(getOr, emptyContainer) { StringMap s = {}; auto expected = "yi"; ASSERT_EQ(getOr(s, "one", "yi"), expected); } TEST(getOr, getFromContainer) { StringMap s; s["one"] = "yi"; s["two"] = "er"; auto expected = "yi"; ASSERT_EQ(getOr(s, "one", "nope"), expected); } } // namespace nix
9,504
C++
.cc
303
28.141914
91
0.471524
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,941
logging.cc
NixOS_nix/src/libutil-tests/logging.cc
#if 0 #include "logging.hh" #include "nixexpr.hh" #include <fstream> #include <gtest/gtest.h> namespace nix { /* ---------------------------------------------------------------------------- * logEI * --------------------------------------------------------------------------*/ const char *test_file = "previous line of code\n" "this is the problem line of code\n" "next line of code\n"; const char *one_liner = "this is the other problem line of code"; TEST(logEI, catpuresBasicProperties) { MakeError(TestError, Error); ErrorInfo::programName = std::optional("error-unit-test"); try { throw TestError("an error for testing purposes"); } catch (Error &e) { testing::internal::CaptureStderr(); logger->logEI(e.info()); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(),"\x1B[31;1merror:\x1B[0m\x1B[34;1m --- TestError --- error-unit-test\x1B[0m\nan error for testing purposes\n"); } } TEST(logEI, jsonOutput) { SymbolTable testTable; auto problem_file = testTable.create("random.nix"); testing::internal::CaptureStderr(); makeJSONLogger(*logger)->logEI({ .name = "error name", .msg = HintFmt("this hint has %1% templated %2%!!", "yellow", "values"), .errPos = Pos(foFile, problem_file, 02, 13) }); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "@nix {\"action\":\"msg\",\"column\":13,\"file\":\"random.nix\",\"level\":0,\"line\":2,\"msg\":\"\\u001b[31;1merror:\\u001b[0m\\u001b[34;1m --- error name --- error-unit-test\\u001b[0m\\n\\u001b[34;1mat: \\u001b[33;1m(2:13)\\u001b[34;1m in file: \\u001b[0mrandom.nix\\n\\nerror without any code lines.\\n\\nthis hint has \\u001b[33;1myellow\\u001b[0m templated \\u001b[33;1mvalues\\u001b[0m!!\",\"raw_msg\":\"this hint has \\u001b[33;1myellow\\u001b[0m templated \\u001b[33;1mvalues\\u001b[0m!!\"}\n"); } TEST(logEI, appendingHintsToPreviousError) { MakeError(TestError, Error); ErrorInfo::programName = std::optional("error-unit-test"); try { auto e = Error("initial error"); throw TestError(e.info()); } catch (Error &e) { ErrorInfo ei = e.info(); ei.msg = HintFmt("%s; subsequent error message.", Uncolored(e.info().msg.str())); testing::internal::CaptureStderr(); logger->logEI(ei); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[31;1merror:\x1B[0m\x1B[34;1m --- TestError --- error-unit-test\x1B[0m\ninitial error; subsequent error message.\n"); } } TEST(logEI, picksUpSystemErrorExitCode) { MakeError(TestError, Error); ErrorInfo::programName = std::optional("error-unit-test"); try { auto x = readFile(-1); } catch (SystemError &e) { testing::internal::CaptureStderr(); logError(e.info()); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[31;1merror:\x1B[0m\x1B[34;1m --- SystemError --- error-unit-test\x1B[0m\nstatting file: \x1B[33;1mBad file descriptor\x1B[0m\n"); } } TEST(logEI, loggingErrorOnInfoLevel) { testing::internal::CaptureStderr(); logger->logEI({ .level = lvlInfo, .name = "Info name", }); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[32;1minfo:\x1B[0m\x1B[34;1m --- Info name --- error-unit-test\x1B[0m\nInfo description\n"); } TEST(logEI, loggingErrorOnTalkativeLevel) { verbosity = lvlTalkative; testing::internal::CaptureStderr(); logger->logEI({ .level = lvlTalkative, .name = "Talkative name", }); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[32;1mtalk:\x1B[0m\x1B[34;1m --- Talkative name --- error-unit-test\x1B[0m\nTalkative description\n"); } TEST(logEI, loggingErrorOnChattyLevel) { verbosity = lvlChatty; testing::internal::CaptureStderr(); logger->logEI({ .level = lvlChatty, .name = "Chatty name", }); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[32;1mchat:\x1B[0m\x1B[34;1m --- Chatty name --- error-unit-test\x1B[0m\nTalkative description\n"); } TEST(logEI, loggingErrorOnDebugLevel) { verbosity = lvlDebug; testing::internal::CaptureStderr(); logger->logEI({ .level = lvlDebug, .name = "Debug name", }); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[33;1mdebug:\x1B[0m\x1B[34;1m --- Debug name --- error-unit-test\x1B[0m\nDebug description\n"); } TEST(logEI, loggingErrorOnVomitLevel) { verbosity = lvlVomit; testing::internal::CaptureStderr(); logger->logEI({ .level = lvlVomit, .name = "Vomit name", }); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[32;1mvomit:\x1B[0m\x1B[34;1m --- Vomit name --- error-unit-test\x1B[0m\nVomit description\n"); } /* ---------------------------------------------------------------------------- * logError * --------------------------------------------------------------------------*/ TEST(logError, logErrorWithoutHintOrCode) { testing::internal::CaptureStderr(); logError({ .name = "name", }); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[31;1merror:\x1B[0m\x1B[34;1m --- name --- error-unit-test\x1B[0m\nerror description\n"); } TEST(logError, logErrorWithPreviousAndNextLinesOfCode) { SymbolTable testTable; auto problem_file = testTable.create(test_file); testing::internal::CaptureStderr(); logError({ .name = "error name", .msg = HintFmt("this hint has %1% templated %2%!!", "yellow", "values"), .errPos = Pos(foString, problem_file, 02, 13), }); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[31;1merror:\x1B[0m\x1B[34;1m --- error name --- error-unit-test\x1B[0m\n\x1B[34;1mat: \x1B[33;1m(2:13)\x1B[34;1m from string\x1B[0m\n\nerror with code lines\n\n 1| previous line of code\n 2| this is the problem line of code\n | \x1B[31;1m^\x1B[0m\n 3| next line of code\n\nthis hint has \x1B[33;1myellow\x1B[0m templated \x1B[33;1mvalues\x1B[0m!!\n"); } TEST(logError, logErrorWithInvalidFile) { SymbolTable testTable; auto problem_file = testTable.create("invalid filename"); testing::internal::CaptureStderr(); logError({ .name = "error name", .msg = HintFmt("this hint has %1% templated %2%!!", "yellow", "values"), .errPos = Pos(foFile, problem_file, 02, 13) }); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[31;1merror:\x1B[0m\x1B[34;1m --- error name --- error-unit-test\x1B[0m\n\x1B[34;1mat: \x1B[33;1m(2:13)\x1B[34;1m in file: \x1B[0minvalid filename\n\nerror without any code lines.\n\nthis hint has \x1B[33;1myellow\x1B[0m templated \x1B[33;1mvalues\x1B[0m!!\n"); } TEST(logError, logErrorWithOnlyHintAndName) { testing::internal::CaptureStderr(); logError({ .name = "error name", .msg = HintFmt("hint %1%", "only"), }); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[31;1merror:\x1B[0m\x1B[34;1m --- error name --- error-unit-test\x1B[0m\nhint \x1B[33;1monly\x1B[0m\n"); } /* ---------------------------------------------------------------------------- * logWarning * --------------------------------------------------------------------------*/ TEST(logWarning, logWarningWithNameDescriptionAndHint) { testing::internal::CaptureStderr(); logWarning({ .name = "name", .msg = HintFmt("there was a %1%", "warning"), }); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[33;1mwarning:\x1B[0m\x1B[34;1m --- name --- error-unit-test\x1B[0m\nwarning description\n\nthere was a \x1B[33;1mwarning\x1B[0m\n"); } TEST(logWarning, logWarningWithFileLineNumAndCode) { SymbolTable testTable; auto problem_file = testTable.create(test_file); testing::internal::CaptureStderr(); logWarning({ .name = "warning name", .msg = HintFmt("this hint has %1% templated %2%!!", "yellow", "values"), .errPos = Pos(foStdin, problem_file, 2, 13), }); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[33;1mwarning:\x1B[0m\x1B[34;1m --- warning name --- error-unit-test\x1B[0m\n\x1B[34;1mat: \x1B[33;1m(2:13)\x1B[34;1m from stdin\x1B[0m\n\nwarning description\n\n 1| previous line of code\n 2| this is the problem line of code\n | \x1B[31;1m^\x1B[0m\n 3| next line of code\n\nthis hint has \x1B[33;1myellow\x1B[0m templated \x1B[33;1mvalues\x1B[0m!!\n"); } /* ---------------------------------------------------------------------------- * traces * --------------------------------------------------------------------------*/ TEST(addTrace, showTracesWithShowTrace) { SymbolTable testTable; auto problem_file = testTable.create(test_file); auto oneliner_file = testTable.create(one_liner); auto invalidfilename = testTable.create("invalid filename"); auto e = AssertionError(ErrorInfo { .name = "wat", .msg = HintFmt("it has been %1% days since our last error", "zero"), .errPos = Pos(foString, problem_file, 2, 13), }); e.addTrace(Pos(foStdin, oneliner_file, 1, 19), "while trying to compute %1%", 42); e.addTrace(std::nullopt, "while doing something without a %1%", "pos"); e.addTrace(Pos(foFile, invalidfilename, 100, 1), "missing %s", "nix file"); testing::internal::CaptureStderr(); loggerSettings.showTrace.assign(true); logError(e.info()); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[31;1merror:\x1B[0m\x1B[34;1m --- AssertionError --- error-unit-test\x1B[0m\n\x1B[34;1mat: \x1B[33;1m(2:13)\x1B[34;1m from string\x1B[0m\n\nshow-traces\n\n 1| previous line of code\n 2| this is the problem line of code\n | \x1B[31;1m^\x1B[0m\n 3| next line of code\n\nit has been \x1B[33;1mzero\x1B[0m days since our last error\n\x1B[34;1m---- show-trace ----\x1B[0m\n\x1B[34;1mtrace: \x1B[0mwhile trying to compute \x1B[33;1m42\x1B[0m\n\x1B[34;1mat: \x1B[33;1m(1:19)\x1B[34;1m from stdin\x1B[0m\n\n 1| this is the other problem line of code\n | \x1B[31;1m^\x1B[0m\n\n\x1B[34;1mtrace: \x1B[0mwhile doing something without a \x1B[33;1mpos\x1B[0m\n\x1B[34;1mtrace: \x1B[0mmissing \x1B[33;1mnix file\x1B[0m\n\x1B[34;1mat: \x1B[33;1m(100:1)\x1B[34;1m in file: \x1B[0minvalid filename\n"); } TEST(addTrace, hideTracesWithoutShowTrace) { SymbolTable testTable; auto problem_file = testTable.create(test_file); auto oneliner_file = testTable.create(one_liner); auto invalidfilename = testTable.create("invalid filename"); auto e = AssertionError(ErrorInfo { .name = "wat", .msg = HintFmt("it has been %1% days since our last error", "zero"), .errPos = Pos(foString, problem_file, 2, 13), }); e.addTrace(Pos(foStdin, oneliner_file, 1, 19), "while trying to compute %1%", 42); e.addTrace(std::nullopt, "while doing something without a %1%", "pos"); e.addTrace(Pos(foFile, invalidfilename, 100, 1), "missing %s", "nix file"); testing::internal::CaptureStderr(); loggerSettings.showTrace.assign(false); logError(e.info()); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[31;1merror:\x1B[0m\x1B[34;1m --- AssertionError --- error-unit-test\x1B[0m\n\x1B[34;1mat: \x1B[33;1m(2:13)\x1B[34;1m from string\x1B[0m\n\nhide traces\n\n 1| previous line of code\n 2| this is the problem line of code\n | \x1B[31;1m^\x1B[0m\n 3| next line of code\n\nit has been \x1B[33;1mzero\x1B[0m days since our last error\n"); } /* ---------------------------------------------------------------------------- * HintFmt * --------------------------------------------------------------------------*/ TEST(HintFmt, percentStringWithoutArgs) { const char *teststr = "this is 100%s correct!"; ASSERT_STREQ( HintFmt(teststr).str().c_str(), teststr); } TEST(HintFmt, fmtToHintfmt) { ASSERT_STREQ( HintFmt(fmt("the color of this this text is %1%", "not yellow")).str().c_str(), "the color of this this text is not yellow"); } TEST(HintFmt, tooFewArguments) { ASSERT_STREQ( HintFmt("only one arg %1% %2%", "fulfilled").str().c_str(), "only one arg " ANSI_WARNING "fulfilled" ANSI_NORMAL " "); } TEST(HintFmt, tooManyArguments) { ASSERT_STREQ( HintFmt("what about this %1% %2%", "%3%", "one", "two").str().c_str(), "what about this " ANSI_WARNING "%3%" ANSI_NORMAL " " ANSI_YELLOW "one" ANSI_NORMAL); } /* ---------------------------------------------------------------------------- * ErrPos * --------------------------------------------------------------------------*/ TEST(errpos, invalidPos) { // contains an invalid symbol, which we should not dereference! Pos invalid; // constructing without access violation. ErrPos ep(invalid); // assignment without access violation. ep = invalid; } } #endif
14,815
C++
.cc
265
45.758491
879
0.554479
NixOS/nix
12,186
1,472
3,401
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false