1
1
Fork 0
mirror of https://github.com/NixOS/nix.git synced 2025-11-17 07:52:43 +01:00

Apply clang-format universally.

* It is tough to contribute to a project that doesn't use a formatter,
* It is extra hard to contribute to a project which has configured the formatter, but ignores it for some files
* Code formatting makes it harder to hide obscure / weird bugs by accident or on purpose,

Let's rip the bandaid off?

Note that PRs currently in flight should be able to be merged relatively easily by applying `clang-format` to their tip prior to merge.
This commit is contained in:
Graham Christensen 2025-07-18 12:47:27 -04:00
parent 41bf87ec70
commit e4f62e4608
587 changed files with 23258 additions and 23135 deletions

View file

@ -19,4 +19,4 @@ int setEnvOs(const OsString & name, const OsString & value)
return setEnv(name.c_str(), value.c_str());
}
}
} // namespace nix

View file

@ -27,7 +27,7 @@ void pollFD(int fd, int events)
throw SysError("poll on file descriptor failed");
}
}
}
} // namespace
std::string readFile(int fd)
{
@ -45,28 +45,31 @@ void readFull(int fd, char * buf, size_t count)
ssize_t res = read(fd, buf, count);
if (res == -1) {
switch (errno) {
case EINTR: continue;
case EINTR:
continue;
case EAGAIN:
pollFD(fd, POLLIN);
continue;
}
throw SysError("reading from file");
}
if (res == 0) throw EndOfFile("unexpected end-of-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();
if (allowInterrupts)
checkInterrupt();
ssize_t res = write(fd, s.data(), s.size());
if (res == -1) {
switch (errno) {
case EINTR: continue;
case EINTR:
continue;
case EAGAIN:
pollFD(fd, POLLOUT);
continue;
@ -78,7 +81,6 @@ void writeFull(int fd, std::string_view s, bool allowInterrupts)
}
}
std::string readLine(int fd, bool eofOk)
{
std::string s;
@ -89,7 +91,8 @@ std::string readLine(int fd, bool eofOk)
ssize_t rd = read(fd, &ch, 1);
if (rd == -1) {
switch (errno) {
case EINTR: continue;
case EINTR:
continue;
case EAGAIN: {
pollFD(fd, POLLIN);
continue;
@ -102,15 +105,14 @@ std::string readLine(int fd, bool eofOk)
return s;
else
throw EndOfFile("unexpected EOF reading a line");
}
else {
if (ch == '\n') return s;
} else {
if (ch == '\n')
return s;
s += ch;
}
}
}
void drainFD(int fd, Sink & sink, bool block)
{
// silence GCC maybe-uninitialized warning in finally
@ -138,9 +140,10 @@ void drainFD(int fd, Sink & sink, bool block)
break;
if (errno != EINTR)
throw SysError("reading from file");
}
else if (rd == 0) break;
else sink({reinterpret_cast<char *>(buf.data()), (size_t) rd});
} else if (rd == 0)
break;
else
sink({reinterpret_cast<char *>(buf.data()), (size_t) rd});
}
}
@ -150,9 +153,11 @@ void Pipe::create()
{
int fds[2];
#if HAVE_PIPE2
if (pipe2(fds, O_CLOEXEC) != 0) throw SysError("creating pipe");
if (pipe2(fds, O_CLOEXEC) != 0)
throw SysError("creating pipe");
#else
if (pipe(fds) != 0) throw SysError("creating pipe");
if (pipe(fds) != 0)
throw SysError("creating pipe");
unix::closeOnExec(fds[0]);
unix::closeOnExec(fds[1]);
#endif
@ -160,17 +165,16 @@ void Pipe::create()
writeSide = fds[1];
}
//////////////////////////////////////////////////////////////////////
#if defined(__linux__) || defined(__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
# if !HAVE_CLOSE_RANGE
return syscall(SYS_close_range, first, last, (unsigned int) flags);
# else
return close_range(first, last, flags);
#endif
# endif
}
#endif
@ -212,13 +216,11 @@ void unix::closeExtraFDs()
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)
if ((prev = fcntl(fd, F_GETFD, 0)) == -1 || fcntl(fd, F_SETFD, prev | FD_CLOEXEC) == -1)
throw SysError("setting close-on-exec flag");
}
}
} // namespace nix

View file

@ -10,7 +10,7 @@ namespace nix {
std::optional<std::filesystem::path> maybePath(PathView path)
{
return { path };
return {path};
}
std::filesystem::path pathNG(PathView path)
@ -18,4 +18,4 @@ std::filesystem::path pathNG(PathView path)
return path;
}
}
} // namespace nix

View file

@ -66,4 +66,4 @@ void setWriteTime(
#endif
}
}
} // namespace nix

View file

@ -127,4 +127,4 @@ public:
}
};
}
} // namespace nix

View file

@ -47,7 +47,7 @@ void _interrupted();
* necessarily match the current thread's mask.
* See saveSignalMask() to set the saved mask to the current mask.
*/
void setChildSignalMask(sigset_t *sigs);
void setChildSignalMask(sigset_t * sigs);
/**
* Start a thread that handles various signals. Also block those signals
@ -73,7 +73,7 @@ void restoreSignals();
void triggerInterrupt();
}
} // namespace unix
static inline void setInterrupted(bool isInterrupted)
{
@ -116,8 +116,8 @@ struct ReceiveInterrupts
ReceiveInterrupts()
: target(pthread_self())
, callback(createInterruptCallback([&]() { pthread_kill(target, SIGUSR1); }))
{ }
{
}
};
}
} // namespace nix

View file

@ -44,4 +44,4 @@ void MuxablePipePollState::iterate(
}
}
}
} // namespace nix

View file

@ -18,4 +18,4 @@ std::filesystem::path::string_type string_to_os_string(std::string_view s)
return std::string{s};
}
}
} // namespace nix

View file

@ -20,51 +20,45 @@
#include <unistd.h>
#ifdef __APPLE__
# include <sys/syscall.h>
# include <sys/syscall.h>
#endif
#ifdef __linux__
# include <sys/prctl.h>
# include <sys/mman.h>
# include <sys/prctl.h>
# include <sys/mman.h>
#endif
#include "util-config-private.hh"
#include "util-unix-config-private.hh"
namespace nix {
Pid::Pid()
{
}
Pid::Pid() {}
Pid::Pid(pid_t pid)
: pid(pid)
{
}
Pid::~Pid()
{
if (pid != -1) kill();
if (pid != -1)
kill();
}
void Pid::operator =(pid_t pid)
void Pid::operator=(pid_t pid)
{
if (this->pid != -1 && this->pid != pid) kill();
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);
@ -87,7 +81,6 @@ int Pid::kill()
return wait();
}
int Pid::wait()
{
assert(pid != -1);
@ -104,19 +97,16 @@ int Pid::wait()
}
}
void Pid::setSeparatePG(bool separatePG)
{
this->separatePG = separatePG;
}
void Pid::setKillSignal(int signal)
{
this->killSignal = signal;
}
pid_t Pid::release()
{
pid_t p = pid;
@ -124,7 +114,6 @@ pid_t Pid::release()
return p;
}
void killUser(uid_t uid)
{
debug("killing all processes running under uid '%1%'", uid);
@ -136,7 +125,6 @@ void killUser(uid_t uid)
fork a process, switch to uid, and send a mass kill. */
Pid pid = startProcess([&] {
if (setuid(uid) == -1)
throw SysError("setting uid");
@ -147,11 +135,14 @@ void killUser(uid_t uid)
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;
if (syscall(SYS_kill, -1, SIGKILL, false) == 0)
break;
#else
if (kill(-1, SIGKILL) == 0) break;
if (kill(-1, SIGKILL) == 0)
break;
#endif
if (errno == ESRCH || errno == EPERM) break; /* no more processes */
if (errno == ESRCH || errno == EPERM)
break; /* no more processes */
if (errno != EINTR)
throw SysError("cannot kill processes for uid '%1%'", uid);
}
@ -169,7 +160,6 @@ void killUser(uid_t uid)
uid | grep -q $uid'. */
}
//////////////////////////////////////////////////////////////////////
using ChildWrapperFunction = std::function<void()>;
@ -177,6 +167,7 @@ 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__
@ -184,22 +175,21 @@ static pid_t doFork(bool allowVfork, ChildWrapperFunction & fun)
#else
pid_t pid = fork();
#endif
if (pid != 0) return pid;
if (pid != 0)
return pid;
fun();
unreachable();
}
#ifdef __linux__
static int childEntry(void * arg)
{
auto & fun = *reinterpret_cast<ChildWrapperFunction*>(arg);
auto & fun = *reinterpret_cast<ChildWrapperFunction *>(arg);
fun();
return 1;
}
#endif
pid_t startProcess(std::function<void()> fun, const ProcessOptions & options)
{
auto newLogger = makeSimpleLogger();
@ -222,8 +212,10 @@ pid_t startProcess(std::function<void()> fun, const ProcessOptions & options)
} catch (std::exception & e) {
try {
std::cerr << options.errorPrefix << e.what() << "\n";
} catch (...) { }
} catch (...) { }
} catch (...) {
}
} catch (...) {
}
if (options.runExitHandlers)
exit(1);
else
@ -233,34 +225,41 @@ pid_t startProcess(std::function<void()> fun, const ProcessOptions & options)
pid_t pid = -1;
if (options.cloneFlags) {
#ifdef __linux__
#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");
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
#else
throw Error("clone flags are only supported on Linux");
#endif
#endif
} else
pid = doFork(options.allowVfork, wrapper);
if (pid == -1) throw SysError("unable to fork");
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)
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});
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));
@ -301,8 +300,10 @@ void runProgram2(const RunOptions & options)
/* Create a pipe. */
Pipe out, in;
if (options.standardOut) out.create();
if (source) in.create();
if (options.standardOut)
out.create();
if (source)
in.create();
ProcessOptions processOptions;
// vfork implies that the environment of the main process and the fork will
@ -313,41 +314,43 @@ void runProgram2(const RunOptions & options)
auto suspension = logger->suspendIf(options.isInteractive);
/* 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");
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");
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);
Strings args_(options.args);
args_.push_front(options.program);
restoreProcessContext();
restoreProcessContext();
if (options.lookupPath)
execvp(options.program.c_str(), stringsToCharPtrs(args_).data());
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());
else
execv(options.program.c_str(), stringsToCharPtrs(args_).data());
throw SysError("executing '%1%'", options.program);
}, processOptions);
throw SysError("executing '%1%'", options.program);
},
processOptions);
out.writeSide.close();
@ -360,7 +363,6 @@ void runProgram2(const RunOptions & options)
writerThread.join();
});
if (source) {
in.readSide.close();
writerThread = std::thread([&] {
@ -390,7 +392,8 @@ void runProgram2(const RunOptions & options)
int status = pid.wait();
/* Wait for the writer thread to finish. */
if (source) promise.get_future().get();
if (source)
promise.get_future().get();
if (status)
throw ExecError(status, "program '%1%' %2%", options.program, statusToString(status));
@ -411,13 +414,12 @@ std::string statusToString(int status)
#else
return fmt("failed due to signal %1%", sig);
#endif
}
else
} else
return "died abnormally";
} else return "succeeded";
} else
return "succeeded";
}
bool statusOk(int status)
{
return WIFEXITED(status) && WEXITSTATUS(status) == 0;
@ -428,7 +430,7 @@ int execvpe(const char * file0, const char * const argv[], const char * const en
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));
return execve(file.c_str(), const_cast<char * const *>(argv), const_cast<char * const *>(envp));
}
}
} // namespace nix

View file

@ -34,15 +34,14 @@ void unix::_interrupted()
}
}
//////////////////////////////////////////////////////////////////////
/* 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 {
struct InterruptCallbacks
{
typedef int64_t Token;
/* We use unique tokens so that we can't accidentally delete the wrong
@ -97,7 +96,6 @@ void unix::triggerInterrupt()
}
}
static sigset_t savedSignalMask;
static bool savedSignalMaskIsSet = false;
@ -105,7 +103,8 @@ void unix::setChildSignalMask(sigset_t * sigs)
{
assert(sigs); // C style function, but think of sigs as a reference
#if (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 1) || (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE) || (defined(_POSIX_SOURCE) && _POSIX_SOURCE)
#if (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 1) || (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE) \
|| (defined(_POSIX_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.
@ -120,7 +119,8 @@ void unix::setChildSignalMask(sigset_t * sigs)
savedSignalMaskIsSet = true;
}
void unix::saveSignalMask() {
void unix::saveSignalMask()
{
if (sigprocmask(SIG_BLOCK, nullptr, &savedSignalMask))
throw SysError("querying signal mask");
@ -166,11 +166,11 @@ void unix::restoreSignals()
throw SysError("restoring signals");
}
/* RAII helper to automatically deregister a callback. */
struct InterruptCallbackImpl : InterruptCallback
{
InterruptCallbacks::Token token;
~InterruptCallbackImpl() override
{
auto interruptCallbacks(_interruptCallbacks.lock());
@ -184,10 +184,10 @@ std::unique_ptr<InterruptCallback> createInterruptCallback(std::function<void()>
auto token = interruptCallbacks->nextToken++;
interruptCallbacks->callbacks.emplace(token, callback);
std::unique_ptr<InterruptCallbackImpl> res {new InterruptCallbackImpl{}};
std::unique_ptr<InterruptCallbackImpl> res{new InterruptCallbackImpl{}};
res->token = token;
return std::unique_ptr<InterruptCallback>(res.release());
}
}
} // namespace nix

View file

@ -23,16 +23,14 @@ 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])
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 = []()
{
static Path homeDir = []() {
std::optional<std::string> unownedUserHomeDir = {};
auto homeDir = getEnv("HOME");
if (homeDir) {
@ -41,7 +39,10 @@ Path getHome()
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);
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()) {
@ -51,7 +52,10 @@ Path getHome()
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);
warn(
"$HOME ('%s') is not owned by you, falling back to the one defined in the 'passwd' file ('%s')",
*unownedUserHomeDir,
*homeDir);
}
}
return *homeDir;
@ -59,8 +63,9 @@ Path getHome()
return homeDir;
}
bool isRootUser() {
bool isRootUser()
{
return getuid() == 0;
}
}
} // namespace nix