Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bd1001a752 | ||
|
|
30008ac474 | ||
|
|
a649b0dab7 | ||
|
|
bbcf2041e1 | ||
|
|
96bcf5928f | ||
|
|
db853cf4fb |
No files matched your search
@@ -9,9 +9,3 @@ endif
|
|||||||
if 'address' in get_option('b_sanitize')
|
if 'address' in get_option('b_sanitize')
|
||||||
deps_other += declare_dependency(sources : 'asan-options.cc')
|
deps_other += declare_dependency(sources : 'asan-options.cc')
|
||||||
endif
|
endif
|
||||||
|
|
||||||
if 'undefined' in get_option('b_sanitize')
|
|
||||||
add_project_arguments('-DNIX_UBSAN_ENABLED=1', language : 'cpp')
|
|
||||||
else
|
|
||||||
add_project_arguments('-DNIX_UBSAN_ENABLED=0', language : 'cpp')
|
|
||||||
endif
|
|
||||||
+1
-1
@@ -710,7 +710,7 @@ void NixRepl::loadFlake(const std::string & flakeRefS)
|
|||||||
try {
|
try {
|
||||||
cwd = std::filesystem::current_path();
|
cwd = std::filesystem::current_path();
|
||||||
} catch (std::filesystem::filesystem_error & e) {
|
} catch (std::filesystem::filesystem_error & e) {
|
||||||
throw SysError("cannot determine current working directory");
|
throw SystemError(e.code(), "cannot determine current working directory");
|
||||||
}
|
}
|
||||||
|
|
||||||
auto flakeRef = parseFlakeRef(fetchSettings, flakeRefS, cwd.string(), true);
|
auto flakeRef = parseFlakeRef(fetchSettings, flakeRefS, cwd.string(), true);
|
||||||
|
|||||||
@@ -11,7 +11,7 @@
|
|||||||
namespace nix::eval_cache {
|
namespace nix::eval_cache {
|
||||||
|
|
||||||
CachedEvalError::CachedEvalError(ref<AttrCursor> cursor, Symbol attr)
|
CachedEvalError::CachedEvalError(ref<AttrCursor> cursor, Symbol attr)
|
||||||
: CloneableError(cursor->root->state, "cached failure of attribute '%s'", cursor->getAttrPathStr(attr))
|
: EvalError(cursor->root->state, "cached failure of attribute '%s'", cursor->getAttrPathStr(attr))
|
||||||
, cursor(cursor)
|
, cursor(cursor)
|
||||||
, attr(attr)
|
, attr(attr)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ namespace nix::eval_cache {
|
|||||||
struct AttrDb;
|
struct AttrDb;
|
||||||
class AttrCursor;
|
class AttrCursor;
|
||||||
|
|
||||||
struct CachedEvalError : CloneableError<CachedEvalError, EvalError>
|
struct CachedEvalError : EvalError
|
||||||
{
|
{
|
||||||
const ref<AttrCursor> cursor;
|
const ref<AttrCursor> cursor;
|
||||||
const Symbol attr;
|
const Symbol attr;
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ class EvalErrorBuilder;
|
|||||||
*
|
*
|
||||||
* Most subclasses should inherit from `EvalError` instead of this class.
|
* Most subclasses should inherit from `EvalError` instead of this class.
|
||||||
*/
|
*/
|
||||||
class EvalBaseError : public CloneableError<EvalBaseError, Error>
|
class EvalBaseError : public Error
|
||||||
{
|
{
|
||||||
template<class T>
|
template<class T>
|
||||||
friend class EvalErrorBuilder;
|
friend class EvalErrorBuilder;
|
||||||
@@ -26,14 +26,14 @@ public:
|
|||||||
EvalState & state;
|
EvalState & state;
|
||||||
|
|
||||||
EvalBaseError(EvalState & state, ErrorInfo && errorInfo)
|
EvalBaseError(EvalState & state, ErrorInfo && errorInfo)
|
||||||
: CloneableError(errorInfo)
|
: Error(errorInfo)
|
||||||
, state(state)
|
, state(state)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
template<typename... Args>
|
template<typename... Args>
|
||||||
explicit EvalBaseError(EvalState & state, const std::string & formatString, const Args &... formatArgs)
|
explicit EvalBaseError(EvalState & state, const std::string & formatString, const Args &... formatArgs)
|
||||||
: CloneableError(formatString, formatArgs...)
|
: Error(formatString, formatArgs...)
|
||||||
, state(state)
|
, state(state)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
@@ -60,23 +60,23 @@ MakeError(InfiniteRecursionError, EvalError);
|
|||||||
* Inherits from EvalBaseError (not EvalError) because resource exhaustion
|
* Inherits from EvalBaseError (not EvalError) because resource exhaustion
|
||||||
* should not be cached.
|
* should not be cached.
|
||||||
*/
|
*/
|
||||||
struct StackOverflowError : public CloneableError<StackOverflowError, EvalBaseError>
|
struct StackOverflowError : public EvalBaseError
|
||||||
{
|
{
|
||||||
StackOverflowError(EvalState & state)
|
StackOverflowError(EvalState & state)
|
||||||
: CloneableError(state, "stack overflow; max-call-depth exceeded")
|
: EvalBaseError(state, "stack overflow; max-call-depth exceeded")
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
MakeError(IFDError, EvalBaseError);
|
MakeError(IFDError, EvalBaseError);
|
||||||
|
|
||||||
struct InvalidPathError : public CloneableError<InvalidPathError, EvalError>
|
struct InvalidPathError : public EvalError
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
Path path;
|
Path path;
|
||||||
|
|
||||||
InvalidPathError(EvalState & state, const Path & path)
|
InvalidPathError(EvalState & state, const Path & path)
|
||||||
: CloneableError(state, "path '%s' is not valid", path)
|
: EvalError(state, "path '%s' is not valid", path)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -9,14 +9,14 @@
|
|||||||
|
|
||||||
namespace nix {
|
namespace nix {
|
||||||
|
|
||||||
class BadNixStringContextElem final : public CloneableError<BadNixStringContextElem, Error>
|
class BadNixStringContextElem : public Error
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
std::string_view raw;
|
std::string_view raw;
|
||||||
|
|
||||||
template<typename... Args>
|
template<typename... Args>
|
||||||
BadNixStringContextElem(std::string_view raw_, const Args &... args)
|
BadNixStringContextElem(std::string_view raw_, const Args &... args)
|
||||||
: CloneableError("")
|
: Error("")
|
||||||
{
|
{
|
||||||
raw = raw_;
|
raw = raw_;
|
||||||
auto hf = HintFmt(args...);
|
auto hf = HintFmt(args...);
|
||||||
|
|||||||
@@ -1312,12 +1312,11 @@ static void prim_warn(EvalState & state, const PosIdx pos, Value ** args, Value
|
|||||||
state.forceString(*args[0], pos, "while evaluating the first argument; the message passed to builtins.warn");
|
state.forceString(*args[0], pos, "while evaluating the first argument; the message passed to builtins.warn");
|
||||||
|
|
||||||
{
|
{
|
||||||
ErrorInfo info{
|
BaseError msg(std::string{msgStr});
|
||||||
.level = lvlWarn,
|
msg.atPos(state.positions[pos]);
|
||||||
.msg = HintFmt(std::string(msgStr)),
|
auto info = msg.info();
|
||||||
.pos = state.positions[pos],
|
info.level = lvlWarn;
|
||||||
.isFromExpr = true,
|
info.isFromExpr = true;
|
||||||
};
|
|
||||||
logWarning(info);
|
logWarning(info);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -74,11 +74,11 @@ namespace nix {
|
|||||||
|
|
||||||
struct GitSourceAccessor;
|
struct GitSourceAccessor;
|
||||||
|
|
||||||
struct GitError final : public CloneableError<GitError, Error>
|
struct GitError : public Error
|
||||||
{
|
{
|
||||||
template<typename... Ts>
|
template<typename... Ts>
|
||||||
GitError(const git_error & error, Ts &&... args)
|
GitError(const git_error & error, Ts &&... args)
|
||||||
: CloneableError("")
|
: Error("")
|
||||||
{
|
{
|
||||||
auto hf = HintFmt(std::forward<Ts>(args)...);
|
auto hf = HintFmt(std::forward<Ts>(args)...);
|
||||||
err.msg = HintFmt("%1%: %2% (libgit2 error code = %3%)", Uncolored(hf.str()), error.message, error.klass);
|
err.msg = HintFmt("%1%: %2% (libgit2 error code = %3%)", Uncolored(hf.str()), error.message, error.klass);
|
||||||
@@ -247,7 +247,8 @@ static void initRepoAtomically(std::filesystem::path & path, GitRepo::Options op
|
|||||||
|| e.code() == std::errc::directory_not_empty) {
|
|| e.code() == std::errc::directory_not_empty) {
|
||||||
return;
|
return;
|
||||||
} else
|
} else
|
||||||
throw SysError("moving temporary git repository from %s to %s", PathFmt(tmpDir), PathFmt(path));
|
throw SystemError(
|
||||||
|
e.code(), "moving temporary git repository from %s to %s", PathFmt(tmpDir), PathFmt(path));
|
||||||
}
|
}
|
||||||
// we successfully moved the repository, so the temporary directory no longer exists.
|
// we successfully moved the repository, so the temporary directory no longer exists.
|
||||||
delTmpDir.cancel();
|
delTmpDir.cancel();
|
||||||
|
|||||||
@@ -28,7 +28,7 @@
|
|||||||
namespace nix {
|
namespace nix {
|
||||||
|
|
||||||
AwsAuthError::AwsAuthError(int errorCode)
|
AwsAuthError::AwsAuthError(int errorCode)
|
||||||
: CloneableError("AWS authentication error: '%s' (%d)", aws_error_str(errorCode), errorCode)
|
: Error("AWS authentication error: '%s' (%d)", aws_error_str(errorCode), errorCode)
|
||||||
, errorCode(errorCode)
|
, errorCode(errorCode)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
#include "nix/store/build/goal.hh"
|
#include "nix/store/build/goal.hh"
|
||||||
#include "nix/store/build/worker.hh"
|
#include "nix/store/build/worker.hh"
|
||||||
#include "nix/store/worker-settings.hh"
|
#include "nix/store/globals.hh"
|
||||||
|
|
||||||
namespace nix {
|
namespace nix {
|
||||||
|
|
||||||
TimedOut::TimedOut(time_t maxDuration)
|
TimedOut::TimedOut(time_t maxDuration)
|
||||||
: CloneableError(BuildResult::Failure::TimedOut, "timed out after %1% seconds", maxDuration)
|
: BuildError(BuildResult::Failure::TimedOut, "timed out after %1% seconds", maxDuration)
|
||||||
, maxDuration(maxDuration)
|
, maxDuration(maxDuration)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,8 +36,8 @@ static void builtinUnpackChannel(const BuiltinBuilderContext & ctx)
|
|||||||
auto target = out / channelName;
|
auto target = out / channelName;
|
||||||
try {
|
try {
|
||||||
std::filesystem::rename(fileName, target);
|
std::filesystem::rename(fileName, target);
|
||||||
} catch (std::filesystem::filesystem_error &) {
|
} catch (std::filesystem::filesystem_error & e) {
|
||||||
throw SysError("failed to rename %1% to %2%", fileName, target.string());
|
throw SystemError(e.code(), "failed to rename %1% to %2%", fileName, target.string());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -60,12 +60,12 @@ namespace {
|
|||||||
using curlSList = std::unique_ptr<::curl_slist, decltype([](::curl_slist * list) { ::curl_slist_free_all(list); })>;
|
using curlSList = std::unique_ptr<::curl_slist, decltype([](::curl_slist * list) { ::curl_slist_free_all(list); })>;
|
||||||
using curlMulti = std::unique_ptr<::CURLM, decltype([](::CURLM * multi) { ::curl_multi_cleanup(multi); })>;
|
using curlMulti = std::unique_ptr<::CURLM, decltype([](::CURLM * multi) { ::curl_multi_cleanup(multi); })>;
|
||||||
|
|
||||||
struct curlMultiError final : CloneableError<curlMultiError, Error>
|
struct curlMultiError : Error
|
||||||
{
|
{
|
||||||
::CURLMcode code;
|
::CURLMcode code;
|
||||||
|
|
||||||
curlMultiError(::CURLMcode code)
|
curlMultiError(::CURLMcode code)
|
||||||
: CloneableError{"unexpected curl multi error: %s", ::curl_multi_strerror(code)}
|
: Error{"unexpected curl multi error: %s", ::curl_multi_strerror(code)}
|
||||||
{
|
{
|
||||||
assert(code != CURLM_OK);
|
assert(code != CURLM_OK);
|
||||||
}
|
}
|
||||||
@@ -1212,7 +1212,7 @@ void FileTransfer::download(
|
|||||||
template<typename... Args>
|
template<typename... Args>
|
||||||
FileTransferError::FileTransferError(
|
FileTransferError::FileTransferError(
|
||||||
FileTransfer::Error error, std::optional<std::string> response, const Args &... args)
|
FileTransfer::Error error, std::optional<std::string> response, const Args &... args)
|
||||||
: CloneableError(args...)
|
: Error(args...)
|
||||||
, error(error)
|
, error(error)
|
||||||
, response(response)
|
, response(response)
|
||||||
{
|
{
|
||||||
|
|||||||
+1
-1
@@ -272,7 +272,7 @@ void LocalStore::findRoots(const Path & path, std::filesystem::file_type type, R
|
|||||||
|| e.code() == std::errc::not_a_directory)
|
|| e.code() == std::errc::not_a_directory)
|
||||||
printInfo("cannot read potential root '%1%'", path);
|
printInfo("cannot read potential root '%1%'", path);
|
||||||
else
|
else
|
||||||
throw;
|
throw SystemError(e.code(), "finding GC roots in '%1%'", path);
|
||||||
}
|
}
|
||||||
|
|
||||||
catch (SystemError & e) {
|
catch (SystemError & e) {
|
||||||
|
|||||||
@@ -34,13 +34,12 @@ struct AwsCredentials
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
class AwsAuthError final : public CloneableError<AwsAuthError, Error>
|
class AwsAuthError : public Error
|
||||||
{
|
{
|
||||||
std::optional<int> errorCode;
|
std::optional<int> errorCode;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
using CloneableError::CloneableError;
|
using Error::Error;
|
||||||
|
|
||||||
AwsAuthError(int errorCode);
|
AwsAuthError(int errorCode);
|
||||||
|
|
||||||
std::optional<int> getErrorCode() const
|
std::optional<int> getErrorCode() const
|
||||||
|
|||||||
@@ -58,7 +58,7 @@ enum struct BuildResultFailureStatus : uint8_t {
|
|||||||
* This is both an exception type (inherits from Error) and serves as
|
* This is both an exception type (inherits from Error) and serves as
|
||||||
* the failure variant in BuildResult::inner.
|
* the failure variant in BuildResult::inner.
|
||||||
*/
|
*/
|
||||||
struct BuildError : public CloneableError<BuildError, Error>
|
struct BuildError : public Error
|
||||||
{
|
{
|
||||||
using Status = BuildResultFailureStatus;
|
using Status = BuildResultFailureStatus;
|
||||||
using enum Status;
|
using enum Status;
|
||||||
@@ -80,7 +80,7 @@ public:
|
|||||||
*/
|
*/
|
||||||
template<typename... Args>
|
template<typename... Args>
|
||||||
BuildError(Status status, const Args &... args)
|
BuildError(Status status, const Args &... args)
|
||||||
: CloneableError(args...)
|
: Error(args...)
|
||||||
, status{status}
|
, status{status}
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
@@ -97,7 +97,7 @@ public:
|
|||||||
* Also used for deserialization.
|
* Also used for deserialization.
|
||||||
*/
|
*/
|
||||||
BuildError(Args args)
|
BuildError(Args args)
|
||||||
: CloneableError(std::move(args.msg))
|
: Error(std::move(args.msg))
|
||||||
, status{args.status}
|
, status{args.status}
|
||||||
, isNonDeterministic{args.isNonDeterministic}
|
, isNonDeterministic{args.isNonDeterministic}
|
||||||
|
|
||||||
@@ -108,7 +108,7 @@ public:
|
|||||||
* Default constructor for deserialization.
|
* Default constructor for deserialization.
|
||||||
*/
|
*/
|
||||||
BuildError()
|
BuildError()
|
||||||
: CloneableError("")
|
: Error("")
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -20,14 +20,14 @@ namespace nix {
|
|||||||
* Denotes a build failure that stemmed from the builder exiting with a
|
* Denotes a build failure that stemmed from the builder exiting with a
|
||||||
* failing exist status.
|
* failing exist status.
|
||||||
*/
|
*/
|
||||||
struct BuilderFailureError final : CloneableError<BuilderFailureError, BuildError>
|
struct BuilderFailureError : BuildError
|
||||||
{
|
{
|
||||||
int builderStatus;
|
int builderStatus;
|
||||||
|
|
||||||
std::string extraMsgAfter;
|
std::string extraMsgAfter;
|
||||||
|
|
||||||
BuilderFailureError(BuildResult::Failure::Status status, int builderStatus, std::string extraMsgAfter)
|
BuilderFailureError(BuildResult::Failure::Status status, int builderStatus, std::string extraMsgAfter)
|
||||||
: CloneableError{
|
: BuildError{
|
||||||
status,
|
status,
|
||||||
/* No message for now, because the caller will make for
|
/* No message for now, because the caller will make for
|
||||||
us, with extra context */
|
us, with extra context */
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
|
|
||||||
namespace nix {
|
namespace nix {
|
||||||
|
|
||||||
struct TimedOut final : CloneableError<TimedOut, BuildError>
|
struct TimedOut : BuildError
|
||||||
{
|
{
|
||||||
time_t maxDuration;
|
time_t maxDuration;
|
||||||
|
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ struct Package
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
class BuildEnvFileConflictError final : public CloneableError<BuildEnvFileConflictError, Error>
|
class BuildEnvFileConflictError : public Error
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
const Path fileA;
|
const Path fileA;
|
||||||
@@ -30,7 +30,7 @@ public:
|
|||||||
int priority;
|
int priority;
|
||||||
|
|
||||||
BuildEnvFileConflictError(const Path fileA, const Path fileB, int priority)
|
BuildEnvFileConflictError(const Path fileA, const Path fileB, int priority)
|
||||||
: CloneableError(
|
: Error(
|
||||||
"Unable to build profile. There is a conflict for the following files:\n"
|
"Unable to build profile. There is a conflict for the following files:\n"
|
||||||
"\n"
|
"\n"
|
||||||
" %1%\n"
|
" %1%\n"
|
||||||
|
|||||||
@@ -403,7 +403,7 @@ ref<FileTransfer> getFileTransfer();
|
|||||||
*/
|
*/
|
||||||
ref<FileTransfer> makeFileTransfer(const FileTransferSettings & settings = fileTransferSettings);
|
ref<FileTransfer> makeFileTransfer(const FileTransferSettings & settings = fileTransferSettings);
|
||||||
|
|
||||||
class FileTransferError final : public CloneableError<FileTransferError, Error>
|
class FileTransferError : public Error
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
FileTransfer::Error error;
|
FileTransfer::Error error;
|
||||||
|
|||||||
@@ -146,7 +146,7 @@ struct RealisedPath
|
|||||||
auto operator<=>(const RealisedPath &) const = default;
|
auto operator<=>(const RealisedPath &) const = default;
|
||||||
};
|
};
|
||||||
|
|
||||||
class MissingRealisation final : public CloneableError<MissingRealisation, Error>
|
class MissingRealisation : public Error
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
MissingRealisation(DrvOutput & outputId)
|
MissingRealisation(DrvOutput & outputId)
|
||||||
@@ -155,7 +155,7 @@ public:
|
|||||||
}
|
}
|
||||||
|
|
||||||
MissingRealisation(std::string_view drv, OutputName outputName)
|
MissingRealisation(std::string_view drv, OutputName outputName)
|
||||||
: CloneableError(
|
: Error(
|
||||||
"cannot operate on output '%s' of the "
|
"cannot operate on output '%s' of the "
|
||||||
"unbuilt derivation '%s'",
|
"unbuilt derivation '%s'",
|
||||||
outputName,
|
outputName,
|
||||||
|
|||||||
@@ -166,7 +166,7 @@ struct SQLiteTxn
|
|||||||
~SQLiteTxn();
|
~SQLiteTxn();
|
||||||
};
|
};
|
||||||
|
|
||||||
struct SQLiteError : CloneableError<SQLiteError, Error>
|
struct SQLiteError : Error
|
||||||
{
|
{
|
||||||
std::string path;
|
std::string path;
|
||||||
std::string errMsg;
|
std::string errMsg;
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
#include "nix/util/archive.hh"
|
#include "nix/util/archive.hh"
|
||||||
#include "nix/util/posix-source-accessor.hh"
|
#include "nix/util/posix-source-accessor.hh"
|
||||||
|
#include "nix/util/posix-source-accessor.hh"
|
||||||
#include "nix/store/store-api.hh"
|
#include "nix/store/store-api.hh"
|
||||||
#include "nix/store/local-fs-store.hh"
|
#include "nix/store/local-fs-store.hh"
|
||||||
#include "nix/store/globals.hh"
|
#include "nix/store/globals.hh"
|
||||||
@@ -109,7 +110,7 @@ std::shared_ptr<SourceAccessor> LocalFSStore::getFSAccessor(const StorePath & pa
|
|||||||
if (!pathExists(absPath))
|
if (!pathExists(absPath))
|
||||||
return nullptr;
|
return nullptr;
|
||||||
}
|
}
|
||||||
return std::make_shared<PosixSourceAccessor>(std::move(absPath));
|
return makeFSSourceAccessor(std::move(absPath));
|
||||||
}
|
}
|
||||||
|
|
||||||
const std::string LocalFSStore::drvsLogDir = "drvs";
|
const std::string LocalFSStore::drvsLogDir = "drvs";
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ static void readProcLink(const std::filesystem::path & file, UncheckedRoots & ro
|
|||||||
if (e.code() == std::errc::no_such_file_or_directory || e.code() == std::errc::permission_denied
|
if (e.code() == std::errc::no_such_file_or_directory || e.code() == std::errc::permission_denied
|
||||||
|| e.code() == std::errc::no_such_process)
|
|| e.code() == std::errc::no_such_process)
|
||||||
return;
|
return;
|
||||||
throw;
|
throw SystemError(e.code(), "reading symlink '%s'", PathFmt(file));
|
||||||
}
|
}
|
||||||
if (buf.is_absolute())
|
if (buf.is_absolute())
|
||||||
roots[buf.string()].emplace(file.string());
|
roots[buf.string()].emplace(file.string());
|
||||||
|
|||||||
@@ -111,8 +111,8 @@ static std::vector<std::string> expandBuilderLines(const std::string & builders)
|
|||||||
std::string text;
|
std::string text;
|
||||||
try {
|
try {
|
||||||
text = readFile(path);
|
text = readFile(path);
|
||||||
} catch (const SysError & e) {
|
} catch (const SystemError & e) {
|
||||||
if (e.errNo != ENOENT)
|
if (!e.is(std::errc::no_such_file_or_directory))
|
||||||
throw;
|
throw;
|
||||||
debug("cannot find machines file '%s'", path);
|
debug("cannot find machines file '%s'", path);
|
||||||
continue;
|
continue;
|
||||||
|
|||||||
@@ -202,14 +202,13 @@ void LocalStore::optimisePath_(
|
|||||||
full. When that happens, it's fine to ignore it: we
|
full. When that happens, it's fine to ignore it: we
|
||||||
just effectively disable deduplication of this
|
just effectively disable deduplication of this
|
||||||
file.
|
file.
|
||||||
TODO: Get rid of errno, use error code.
|
|
||||||
*/
|
*/
|
||||||
printInfo("cannot link %s to '%s': %s", PathFmt(linkPath), path, strerror(errno));
|
printInfo("cannot link %s to '%s': %s", PathFmt(linkPath), path, e.code().message());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
else
|
else
|
||||||
throw;
|
throw SystemError(e.code(), "creating hard link from %1% to %2%", PathFmt(linkPath), path);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -250,7 +249,7 @@ void LocalStore::optimisePath_(
|
|||||||
printInfo("%1% has maximum number of links", PathFmt(linkPath));
|
printInfo("%1% has maximum number of links", PathFmt(linkPath));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
throw;
|
throw SystemError(e.code(), "creating hard link from %1% to %2%", PathFmt(linkPath), PathFmt(tempLink));
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Atomically replace the old file with the new hard link. */
|
/* Atomically replace the old file with the new hard link. */
|
||||||
@@ -271,7 +270,7 @@ void LocalStore::optimisePath_(
|
|||||||
debug("%s has reached maximum number of links", PathFmt(linkPath));
|
debug("%s has reached maximum number of links", PathFmt(linkPath));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
throw;
|
throw SystemError(e.code(), "renaming %1% to %2%", PathFmt(tempLink), path);
|
||||||
}
|
}
|
||||||
|
|
||||||
stats.filesLinked++;
|
stats.filesLinked++;
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
#include "nix/util/util.hh"
|
#include "nix/util/util.hh"
|
||||||
#include "nix/store/store-api.hh"
|
#include "nix/store/store-api.hh"
|
||||||
#include "nix/store/globals.hh"
|
#include "nix/store/globals.hh"
|
||||||
|
#include "nix/util/file-system-at.hh"
|
||||||
#include "store-config-private.hh"
|
#include "store-config-private.hh"
|
||||||
|
|
||||||
#if NIX_SUPPORT_ACL
|
#if NIX_SUPPORT_ACL
|
||||||
|
|||||||
@@ -103,7 +103,7 @@ static void removeFile(const std::filesystem::path & path)
|
|||||||
try {
|
try {
|
||||||
std::filesystem::remove(path);
|
std::filesystem::remove(path);
|
||||||
} catch (std::filesystem::filesystem_error & e) {
|
} catch (std::filesystem::filesystem_error & e) {
|
||||||
throw SysError("removing file %1%", PathFmt(path));
|
throw SystemError(e.code(), "removing file %1%", PathFmt(path));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -324,8 +324,6 @@ std::filesystem::path getDefaultProfile(ProfileDirsOptions settings)
|
|||||||
return absPath(readLink(profileLink), &linkDir);
|
return absPath(readLink(profileLink), &linkDir);
|
||||||
} catch (Error &) {
|
} catch (Error &) {
|
||||||
return profileLink;
|
return profileLink;
|
||||||
} catch (std::filesystem::filesystem_error &) {
|
|
||||||
return profileLink;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ namespace nix {
|
|||||||
|
|
||||||
SQLiteError::SQLiteError(
|
SQLiteError::SQLiteError(
|
||||||
const char * path, const char * errMsg, int errNo, int extendedErrNo, int offset, HintFmt && hf)
|
const char * path, const char * errMsg, int errNo, int extendedErrNo, int offset, HintFmt && hf)
|
||||||
: CloneableError("")
|
: Error("")
|
||||||
, path(path)
|
, path(path)
|
||||||
, errMsg(errMsg)
|
, errMsg(errMsg)
|
||||||
, errNo(errNo)
|
, errNo(errNo)
|
||||||
|
|||||||
+2
-2
@@ -18,11 +18,11 @@ static std::string parsePublicHostKey(std::string_view host, std::string_view ss
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class InvalidSSHAuthority final : public CloneableError<InvalidSSHAuthority, Error>
|
class InvalidSSHAuthority : public Error
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
InvalidSSHAuthority(const ParsedURL::Authority & authority, std::string_view reason)
|
InvalidSSHAuthority(const ParsedURL::Authority & authority, std::string_view reason)
|
||||||
: CloneableError("invalid SSH authority: '%s': %s", authority.to_string(), reason)
|
: Error("invalid SSH authority: '%s': %s", authority.to_string(), reason)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -55,10 +55,10 @@
|
|||||||
|
|
||||||
namespace nix {
|
namespace nix {
|
||||||
|
|
||||||
struct NotDeterministic final : CloneableError<NotDeterministic, BuildError>
|
struct NotDeterministic : BuildError
|
||||||
{
|
{
|
||||||
NotDeterministic(auto &&... args)
|
NotDeterministic(auto &&... args)
|
||||||
: CloneableError(BuildResult::Failure::NotDeterministic, args...)
|
: BuildError(BuildResult::Failure::NotDeterministic, args...)
|
||||||
{
|
{
|
||||||
isNonDeterministic = true;
|
isNonDeterministic = true;
|
||||||
}
|
}
|
||||||
@@ -758,7 +758,7 @@ std::optional<Descriptor> DerivationBuilderImpl::startBuild()
|
|||||||
|
|
||||||
/* The TOCTOU between the previous mkdir call and this open call is unavoidable due to
|
/* The TOCTOU between the previous mkdir call and this open call is unavoidable due to
|
||||||
POSIX semantics.*/
|
POSIX semantics.*/
|
||||||
tmpDirFd = AutoCloseFD{open(tmpDir.c_str(), O_RDONLY | O_NOFOLLOW | O_DIRECTORY)};
|
tmpDirFd = openDirectory(tmpDir, /*followFinalSymlink=*/false);
|
||||||
if (!tmpDirFd)
|
if (!tmpDirFd)
|
||||||
throw SysError("failed to open the build temporary directory descriptor %1%", PathFmt(tmpDir));
|
throw SysError("failed to open the build temporary directory descriptor %1%", PathFmt(tmpDir));
|
||||||
|
|
||||||
@@ -1269,7 +1269,7 @@ void DerivationBuilderImpl::writeBuilderFile(const std::string & name, std::stri
|
|||||||
openat(tmpDirFd.get(), name.c_str(), O_WRONLY | O_TRUNC | O_CREAT | O_CLOEXEC | O_EXCL | O_NOFOLLOW, 0666)};
|
openat(tmpDirFd.get(), name.c_str(), O_WRONLY | O_TRUNC | O_CREAT | O_CLOEXEC | O_EXCL | O_NOFOLLOW, 0666)};
|
||||||
if (!fd)
|
if (!fd)
|
||||||
throw SysError("creating file %s", PathFmt(path));
|
throw SysError("creating file %s", PathFmt(path));
|
||||||
writeFile(fd, path, contents);
|
writeFile(fd.get(), contents);
|
||||||
chownToBuilder(fd.get(), path);
|
chownToBuilder(fd.get(), path);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
#include "nix/store/pathlocks.hh"
|
#include "nix/store/pathlocks.hh"
|
||||||
#include "nix/util/file-system.hh"
|
#include "nix/util/file-system-at.hh"
|
||||||
#include "nix/util/util.hh"
|
#include "nix/util/util.hh"
|
||||||
#include "nix/util/sync.hh"
|
#include "nix/util/sync.hh"
|
||||||
#include "nix/util/signals.hh"
|
#include "nix/util/signals.hh"
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
#include <gtest/gtest.h>
|
#include <gtest/gtest.h>
|
||||||
#include <gmock/gmock.h>
|
|
||||||
|
|
||||||
#include "nix/util/file-system-at.hh"
|
#include "nix/util/file-system-at.hh"
|
||||||
#include "nix/util/file-system.hh"
|
#include "nix/util/file-system.hh"
|
||||||
#include "nix/util/fs-sink.hh"
|
#include "nix/util/fs-sink.hh"
|
||||||
|
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
namespace nix {
|
namespace nix {
|
||||||
|
|
||||||
/* ----------------------------------------------------------------------------
|
/* ----------------------------------------------------------------------------
|
||||||
|
|||||||
@@ -319,7 +319,7 @@ TEST(chmodIfNeeded, works)
|
|||||||
|
|
||||||
TEST(chmodIfNeeded, nonexistent)
|
TEST(chmodIfNeeded, nonexistent)
|
||||||
{
|
{
|
||||||
ASSERT_THROW(chmodIfNeeded("/schnitzel/darmstadt/pommes", 0755), SysError);
|
ASSERT_THROW(chmodIfNeeded("/schnitzel/darmstadt/pommes", 0755), SystemError);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ----------------------------------------------------------------------------
|
/* ----------------------------------------------------------------------------
|
||||||
@@ -340,7 +340,7 @@ TEST(DirectoryIterator, works)
|
|||||||
|
|
||||||
TEST(DirectoryIterator, nonexistent)
|
TEST(DirectoryIterator, nonexistent)
|
||||||
{
|
{
|
||||||
ASSERT_THROW(DirectoryIterator("/schnitzel/darmstadt/pommes"), SysError);
|
ASSERT_THROW(DirectoryIterator("/schnitzel/darmstadt/pommes"), SystemError);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ----------------------------------------------------------------------------
|
/* ----------------------------------------------------------------------------
|
||||||
|
|||||||
@@ -91,9 +91,7 @@ TEST_F(FSSourceAccessorTest, works)
|
|||||||
{
|
{
|
||||||
RestoreSink sink(false);
|
RestoreSink sink(false);
|
||||||
sink.dstPath = tmpDir;
|
sink.dstPath = tmpDir;
|
||||||
#ifndef _WIN32
|
|
||||||
sink.dirFd = openDirectory(tmpDir);
|
sink.dirFd = openDirectory(tmpDir);
|
||||||
#endif
|
|
||||||
sink.createDirectory(CanonPath("subdir"));
|
sink.createDirectory(CanonPath("subdir"));
|
||||||
sink.createRegularFile(CanonPath("file1"), [](CreateRegularFileSink & crf) { crf("content1"); });
|
sink.createRegularFile(CanonPath("file1"), [](CreateRegularFileSink & crf) { crf("content1"); });
|
||||||
sink.createRegularFile(CanonPath("subdir/file2"), [](CreateRegularFileSink & crf) { crf("content2"); });
|
sink.createRegularFile(CanonPath("subdir/file2"), [](CreateRegularFileSink & crf) { crf("content2"); });
|
||||||
@@ -137,4 +135,34 @@ TEST_F(FSSourceAccessorTest, works)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ----------------------------------------------------------------------------
|
||||||
|
* RestoreSink non-directory at root (no dirFd)
|
||||||
|
* --------------------------------------------------------------------------*/
|
||||||
|
|
||||||
|
TEST_F(FSSourceAccessorTest, RestoreSinkRegularFileAtRoot)
|
||||||
|
{
|
||||||
|
auto filePath = tmpDir / "rootfile";
|
||||||
|
{
|
||||||
|
RestoreSink sink(false);
|
||||||
|
sink.dstPath = filePath;
|
||||||
|
// No dirFd set - this tests the !dirFd path
|
||||||
|
sink.createRegularFile(CanonPath::root, [](CreateRegularFileSink & crf) { crf("root content"); });
|
||||||
|
}
|
||||||
|
|
||||||
|
EXPECT_THAT(makeFSSourceAccessor(filePath), HasContents(CanonPath::root, "root content"));
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST_F(FSSourceAccessorTest, RestoreSinkSymlinkAtRoot)
|
||||||
|
{
|
||||||
|
auto linkPath = tmpDir / "rootlink";
|
||||||
|
{
|
||||||
|
RestoreSink sink(false);
|
||||||
|
sink.dstPath = linkPath;
|
||||||
|
// No dirFd set - this tests the !dirFd path
|
||||||
|
sink.createSymlink(CanonPath::root, "symlink_target");
|
||||||
|
}
|
||||||
|
|
||||||
|
EXPECT_THAT(makeFSSourceAccessor(linkPath), HasSymlink(CanonPath::root, "symlink_target"));
|
||||||
|
}
|
||||||
|
|
||||||
} // namespace nix
|
} // namespace nix
|
||||||
@@ -0,0 +1,285 @@
|
|||||||
|
// FIXME: detect in meson
|
||||||
|
#define HAVE_OPENAT2 1
|
||||||
|
#define HAVE_OPENAT 1
|
||||||
|
|
||||||
|
#include "util-config-private.hh"
|
||||||
|
#include "nix/util/signals.hh"
|
||||||
|
#include "nix/util/directory-source-accessor.hh"
|
||||||
|
#include "nix/util/posix-source-accessor.hh"
|
||||||
|
|
||||||
|
#if defined(__linux__) && HAVE_OPENAT2
|
||||||
|
# include <sys/syscall.h>
|
||||||
|
# include <linux/openat2.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include <atomic>
|
||||||
|
#include <ranges>
|
||||||
|
|
||||||
|
namespace nix {
|
||||||
|
|
||||||
|
#if HAVE_OPENAT
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
class DirFdSourceAccessor : public SourceAccessor
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* File descriptor of the root directory.
|
||||||
|
*/
|
||||||
|
AutoCloseFD dirFd;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Path corresponding to the accessor.
|
||||||
|
* @warning Do not use for any file operations!
|
||||||
|
*/
|
||||||
|
std::filesystem::path root;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The most recent mtime seen by lstat(). This is a hack to
|
||||||
|
* support dumpPathAndGetMtime(). Should remove this eventually.
|
||||||
|
*/
|
||||||
|
time_t mtime = 0;
|
||||||
|
|
||||||
|
bool trackLastModified = false;
|
||||||
|
|
||||||
|
AutoCloseFD openFile(const CanonPath & path, int flags)
|
||||||
|
{
|
||||||
|
if (path.isRoot())
|
||||||
|
return ::openat(dirFd.get(), ".", flags);
|
||||||
|
|
||||||
|
# if defined(__linux__) && HAVE_OPENAT2
|
||||||
|
/* Cache the result of whether openat2 is not supported. */
|
||||||
|
static std::atomic_flag openat2Unsupported = ATOMIC_FLAG_INIT;
|
||||||
|
|
||||||
|
if (!openat2Unsupported.test()) {
|
||||||
|
/* No glibc wrapper yet, but there's a patch:
|
||||||
|
* https://patchwork.sourceware.org/project/glibc/patch/20251029200519.3203914-1-adhemerval.zanella@linaro.org/
|
||||||
|
*/
|
||||||
|
auto how = ::open_how{
|
||||||
|
.flags = static_cast<decltype(::open_how::flags)>(flags),
|
||||||
|
/* Symlinks are disallowed. RESOLVE_BENEATH is a bit overkill, since
|
||||||
|
CanonPath has the invariant of not having any `..` components, but
|
||||||
|
that's good practice anyway. */
|
||||||
|
.resolve = RESOLVE_NO_SYMLINKS | RESOLVE_BENEATH,
|
||||||
|
};
|
||||||
|
|
||||||
|
auto res = ::syscall(__NR_openat2, dirFd.get(), path.rel_c_str(), &how, sizeof(how));
|
||||||
|
if (res < 0 && errno == ENOSYS) {
|
||||||
|
/* Cache that the syscall is not supported and fall through to openat. */
|
||||||
|
openat2Unsupported.test_and_set();
|
||||||
|
} else {
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
# endif
|
||||||
|
|
||||||
|
AutoCloseFD parentFd;
|
||||||
|
auto nrComponents = std::ranges::distance(path);
|
||||||
|
auto components = std::views::take(path, nrComponents - 1); /* Everything but last component */
|
||||||
|
auto getParentFd = [&]() { return parentFd ? parentFd.get() : dirFd.get(); };
|
||||||
|
|
||||||
|
/* This rather convoluted loop is necessary to avoid TOCTOU when validating that
|
||||||
|
no inner path component is a symlink. */
|
||||||
|
for (auto it = components.begin(); it != components.end(); ++it) {
|
||||||
|
std::string_view component = *it;
|
||||||
|
parentFd = ::openat(
|
||||||
|
getParentFd(), /* First iteration uses dirFd. */
|
||||||
|
std::string(component).c_str(), /* Copy into a string to make NUL terminated. */
|
||||||
|
O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC |
|
||||||
|
# ifdef __linux__
|
||||||
|
O_PATH /* Linux-specific optimization. Files are open only for path resolution purposes. */
|
||||||
|
# endif
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!parentFd) {
|
||||||
|
/* Construct the CanonPath for error message. */
|
||||||
|
auto path2 = std::ranges::fold_left(components.begin(), ++it, CanonPath::root, [](auto lhs, auto rhs) {
|
||||||
|
lhs.push(rhs);
|
||||||
|
return lhs;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (errno == ELOOP)
|
||||||
|
/* Do not allow any simlinks in internal path components.
|
||||||
|
This is what is necessary to emulate it without RESOLVE_NO_SYMLINKS. */
|
||||||
|
throw Error("path '%s' is a symlink", showPath(path2));
|
||||||
|
|
||||||
|
return AutoCloseFD();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ::openat(getParentFd(), std::string(path.baseName().value()).c_str(), flags);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<struct ::stat> maybeLstatImpl(const CanonPath & path)
|
||||||
|
{
|
||||||
|
std::optional<struct ::stat> st{std::in_place};
|
||||||
|
|
||||||
|
if (path.isRoot()) {
|
||||||
|
if (::fstat(dirFd.get(), &*st)) /* Is already open. */
|
||||||
|
throw SysError("getting status of '%s'", showPath(path));
|
||||||
|
return st;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto parentPath = path.parent().value();
|
||||||
|
auto fd = openFile(parentPath, O_PATH | O_NOFOLLOW | O_CLOEXEC | O_DIRECTORY);
|
||||||
|
if (!fd) {
|
||||||
|
if (errno == ENOENT || errno == ENOTDIR)
|
||||||
|
return std::nullopt;
|
||||||
|
throw SysError("opening parent path of '%s'", showPath(path));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Should have the same semantics as lstat on a path. */
|
||||||
|
if (::fstatat(fd.get(), std::string(path.baseName().value()).c_str(), &*st, AT_SYMLINK_NOFOLLOW)) {
|
||||||
|
if (errno == ENOENT || errno == ENOTDIR)
|
||||||
|
st.reset();
|
||||||
|
else
|
||||||
|
throw SysError("getting status of '%s'", showPath(path));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The contract is that trackLastModified implies that the caller uses the accessor
|
||||||
|
from a single thread. Thus this is not a CAS loop. */
|
||||||
|
if (trackLastModified)
|
||||||
|
mtime = std::max(mtime, st->st_mtime);
|
||||||
|
|
||||||
|
return st;
|
||||||
|
}
|
||||||
|
|
||||||
|
public:
|
||||||
|
DirFdSourceAccessor(AutoCloseFD rootFd_, std::filesystem::path root_, bool trackLastModified)
|
||||||
|
: dirFd(std::move(rootFd_))
|
||||||
|
, root(std::move(root_))
|
||||||
|
, trackLastModified(trackLastModified)
|
||||||
|
{
|
||||||
|
if (root != root.root_path()) /* Don't prefix root directory. */
|
||||||
|
displayPrefix = root.string();
|
||||||
|
}
|
||||||
|
|
||||||
|
void readFile(const CanonPath & path, Sink & sink, std::function<void(uint64_t)> sizeCallback) override
|
||||||
|
{
|
||||||
|
auto fd = openFile(path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
|
||||||
|
|
||||||
|
auto size = getFileSize(fd.get());
|
||||||
|
sizeCallback(size);
|
||||||
|
drainFD(fd.get(), sink, {.expectedSize = size});
|
||||||
|
}
|
||||||
|
|
||||||
|
bool pathExists(const CanonPath & path) override
|
||||||
|
{
|
||||||
|
return maybeLstatImpl(path).has_value();
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<Stat> maybeLstat(const CanonPath & path) override
|
||||||
|
{
|
||||||
|
// TODO: Deduplicate with PosixSourceAccessor.
|
||||||
|
|
||||||
|
auto st = maybeLstatImpl(path);
|
||||||
|
if (!st)
|
||||||
|
return std::nullopt;
|
||||||
|
|
||||||
|
/* The contract is that trackLastModified implies that the caller uses the accessor
|
||||||
|
from a single thread. Thus this is not a CAS loop. */
|
||||||
|
if (trackLastModified)
|
||||||
|
mtime = std::max(mtime, st->st_mtime);
|
||||||
|
|
||||||
|
return PosixSourceAccessor::makeStat(*st);
|
||||||
|
}
|
||||||
|
|
||||||
|
DirEntries readDirectory(const CanonPath & path) override
|
||||||
|
{
|
||||||
|
auto fd = openFile(path, O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
|
||||||
|
if (!fd)
|
||||||
|
throw SysError("opening directory '%1%'", path);
|
||||||
|
|
||||||
|
auto dir = AutoCloseDir{::fdopendir(fd.get())};
|
||||||
|
if (!dir)
|
||||||
|
throw SysError("opening directory '%1%'", path);
|
||||||
|
|
||||||
|
fd.release();
|
||||||
|
|
||||||
|
DirEntries entries;
|
||||||
|
struct dirent * dirent;
|
||||||
|
|
||||||
|
while (errno = 0, dirent = ::readdir(dir.get())) {
|
||||||
|
checkInterrupt();
|
||||||
|
std::string name = dirent->d_name;
|
||||||
|
if (name == "." || name == "..")
|
||||||
|
continue;
|
||||||
|
|
||||||
|
auto type = [&]() -> std::optional<Type> {
|
||||||
|
switch (dirent->d_type) {
|
||||||
|
case DT_REG:
|
||||||
|
return tRegular;
|
||||||
|
case DT_DIR:
|
||||||
|
return tDirectory;
|
||||||
|
case DT_LNK:
|
||||||
|
return tSymlink;
|
||||||
|
case DT_BLK:
|
||||||
|
return tBlock;
|
||||||
|
case DT_CHR:
|
||||||
|
return tChar;
|
||||||
|
case DT_FIFO:
|
||||||
|
return tFifo;
|
||||||
|
case DT_SOCK:
|
||||||
|
return tSocket;
|
||||||
|
case DT_UNKNOWN:
|
||||||
|
default:
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
}();
|
||||||
|
|
||||||
|
entries.emplace(std::move(name), type);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (errno)
|
||||||
|
throw SysError("reading directory '%1%'", showPath(path));
|
||||||
|
|
||||||
|
return entries;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string readLink(const CanonPath & path) override
|
||||||
|
{
|
||||||
|
if (path.isRoot())
|
||||||
|
throw Error("file '%s' is not a symbolic link", path);
|
||||||
|
|
||||||
|
auto parentPath = path.parent().value();
|
||||||
|
auto basename = std::string(path.baseName().value());
|
||||||
|
|
||||||
|
auto parentFd = openFile(
|
||||||
|
parentPath,
|
||||||
|
O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC |
|
||||||
|
# ifdef __linux__
|
||||||
|
O_PATH
|
||||||
|
# endif
|
||||||
|
);
|
||||||
|
if (!parentFd)
|
||||||
|
throw SysError("opening path '%1%'", showPath(parentPath));
|
||||||
|
|
||||||
|
std::string target;
|
||||||
|
target.resize(PATH_MAX);
|
||||||
|
auto len = ::readlinkat(parentFd.get(), basename.c_str(), target.data(), target.size());
|
||||||
|
if (len < 0)
|
||||||
|
throw SysError("reading link '%1%'", showPath(path));
|
||||||
|
target.resize(len);
|
||||||
|
return target;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<std::filesystem::path> getPhysicalPath(const CanonPath & path) override
|
||||||
|
{
|
||||||
|
return root / path.rel();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
|
ref<SourceAccessor> makeDirectorySourceAccessor(AutoCloseFD fd, std::filesystem::path root, bool trackLastModified)
|
||||||
|
{
|
||||||
|
#if HAVE_OPENAT
|
||||||
|
return make_ref<DirFdSourceAccessor>(std::move(fd), std::move(root), trackLastModified);
|
||||||
|
#else
|
||||||
|
return make_ref<PosixSourceAccessor>(std::move(root), trackLastModified);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace nix
|
||||||
@@ -378,7 +378,7 @@ std::set<ExperimentalFeature> parseFeatures(const StringSet & rawFeatures)
|
|||||||
}
|
}
|
||||||
|
|
||||||
MissingExperimentalFeature::MissingExperimentalFeature(ExperimentalFeature feature, std::string reason)
|
MissingExperimentalFeature::MissingExperimentalFeature(ExperimentalFeature feature, std::string reason)
|
||||||
: CloneableError(
|
: Error(
|
||||||
"experimental Nix feature '%1%' is disabled%2%; add '--extra-experimental-features %1%' to enable it",
|
"experimental Nix feature '%1%' is disabled%2%; add '--extra-experimental-features %1%' to enable it",
|
||||||
showExperimentalFeature(feature),
|
showExperimentalFeature(feature),
|
||||||
Uncolored(optionalBracket(" (", reason, ")")))
|
Uncolored(optionalBracket(" (", reason, ")")))
|
||||||
|
|||||||
@@ -184,24 +184,6 @@ void AutoCloseFD::close()
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void AutoCloseFD::fsync() const
|
|
||||||
{
|
|
||||||
if (fd != INVALID_DESCRIPTOR) {
|
|
||||||
int result;
|
|
||||||
result =
|
|
||||||
#ifdef _WIN32
|
|
||||||
::FlushFileBuffers(fd)
|
|
||||||
#elif defined(__APPLE__)
|
|
||||||
::fcntl(fd, F_FULLFSYNC)
|
|
||||||
#else
|
|
||||||
::fsync(fd)
|
|
||||||
#endif
|
|
||||||
;
|
|
||||||
if (result == -1)
|
|
||||||
throw NativeSysError("fsync file descriptor %1%", fd);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void AutoCloseFD::startFsync() const
|
void AutoCloseFD::startFsync() const
|
||||||
{
|
{
|
||||||
#ifdef __linux__
|
#ifdef __linux__
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
#include "nix/util/file-system-at.hh"
|
||||||
|
|
||||||
|
namespace nix {
|
||||||
|
|
||||||
|
std::optional<PosixStat> maybeFstatat(Descriptor dirFd, const CanonPath & path)
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
return fstatat(dirFd, path);
|
||||||
|
} catch (SystemError & e) {
|
||||||
|
if (e.is(std::errc::no_such_file_or_directory) || e.is(std::errc::not_a_directory))
|
||||||
|
return std::nullopt;
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace nix
|
||||||
+34
-59
@@ -40,9 +40,9 @@ DirectoryIterator::DirectoryIterator(const std::filesystem::path & p)
|
|||||||
// **Attempt to create the underlying directory_iterator**
|
// **Attempt to create the underlying directory_iterator**
|
||||||
it_ = std::filesystem::directory_iterator(p);
|
it_ = std::filesystem::directory_iterator(p);
|
||||||
} catch (const std::filesystem::filesystem_error & e) {
|
} catch (const std::filesystem::filesystem_error & e) {
|
||||||
// **Catch filesystem_error and throw SysError**
|
// **Catch filesystem_error and throw SystemError**
|
||||||
// Adapt the error message as needed for SysError
|
// Adapt the error message as needed for SystemError
|
||||||
throw SysError("cannot read directory %s", PathFmt(p));
|
throw SystemError(e.code(), "cannot read directory %s", PathFmt(p));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -195,71 +195,42 @@ bool isDirOrInDir(const std::filesystem::path & path, const std::filesystem::pat
|
|||||||
return path == dir || isInDir(path, dir);
|
return path == dir || isInDir(path, dir);
|
||||||
}
|
}
|
||||||
|
|
||||||
#ifdef _WIN32
|
|
||||||
# define STAT _wstat64
|
|
||||||
# define LSTAT _wstat64
|
|
||||||
#else
|
|
||||||
# define STAT stat
|
|
||||||
# define LSTAT lstat
|
|
||||||
#endif
|
|
||||||
|
|
||||||
PosixStat stat(const std::filesystem::path & path)
|
PosixStat stat(const std::filesystem::path & path)
|
||||||
{
|
|
||||||
PosixStat st;
|
|
||||||
if (STAT(path.c_str(), &st))
|
|
||||||
throw SysError("getting status of %s", PathFmt(path));
|
|
||||||
return st;
|
|
||||||
}
|
|
||||||
|
|
||||||
PosixStat lstat(const std::filesystem::path & path)
|
|
||||||
{
|
|
||||||
PosixStat st;
|
|
||||||
if (LSTAT(path.c_str(), &st))
|
|
||||||
throw SysError("getting status of %s", PathFmt(path));
|
|
||||||
return st;
|
|
||||||
}
|
|
||||||
|
|
||||||
PosixStat fstat(int fd)
|
|
||||||
{
|
{
|
||||||
PosixStat st;
|
PosixStat st;
|
||||||
if (
|
if (
|
||||||
#ifdef _WIN32
|
#ifdef _WIN32
|
||||||
_fstat64
|
_wstat64
|
||||||
#else
|
#else
|
||||||
::fstat
|
::stat
|
||||||
#endif
|
#endif
|
||||||
(fd, &st))
|
(path.c_str(), &st))
|
||||||
throw SysError("getting status of fd %d", fd);
|
throw SysError("getting status of %s", PathFmt(path));
|
||||||
return st;
|
return st;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::optional<PosixStat> maybeStat(const std::filesystem::path & path)
|
std::optional<PosixStat> maybeStat(const std::filesystem::path & path)
|
||||||
{
|
{
|
||||||
std::optional<PosixStat> st{std::in_place};
|
try {
|
||||||
if (STAT(path.c_str(), &*st)) {
|
return stat(path);
|
||||||
if (errno == ENOENT || errno == ENOTDIR)
|
} catch (SystemError & e) {
|
||||||
st.reset();
|
if (e.is(std::errc::no_such_file_or_directory) || e.is(std::errc::not_a_directory))
|
||||||
else
|
return std::nullopt;
|
||||||
throw SysError("getting status of %s", PathFmt(path));
|
throw;
|
||||||
}
|
}
|
||||||
return st;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
std::optional<PosixStat> maybeLstat(const std::filesystem::path & path)
|
std::optional<PosixStat> maybeLstat(const std::filesystem::path & path)
|
||||||
{
|
{
|
||||||
std::optional<PosixStat> st{std::in_place};
|
try {
|
||||||
if (LSTAT(path.c_str(), &*st)) {
|
return lstat(path);
|
||||||
if (errno == ENOENT || errno == ENOTDIR)
|
} catch (SystemError & e) {
|
||||||
st.reset();
|
if (e.is(std::errc::no_such_file_or_directory) || e.is(std::errc::not_a_directory))
|
||||||
else
|
return std::nullopt;
|
||||||
throw SysError("getting status of %s", PathFmt(path));
|
throw;
|
||||||
}
|
}
|
||||||
return st;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#undef STAT
|
|
||||||
#undef LSTAT
|
|
||||||
|
|
||||||
bool pathExists(const std::filesystem::path & path)
|
bool pathExists(const std::filesystem::path & path)
|
||||||
{
|
{
|
||||||
return maybeLstat(path.string()).has_value();
|
return maybeLstat(path.string()).has_value();
|
||||||
@@ -280,7 +251,11 @@ bool pathAccessible(const std::filesystem::path & path)
|
|||||||
std::filesystem::path readLink(const std::filesystem::path & path)
|
std::filesystem::path readLink(const std::filesystem::path & path)
|
||||||
{
|
{
|
||||||
checkInterrupt();
|
checkInterrupt();
|
||||||
return std::filesystem::read_symlink(path);
|
try {
|
||||||
|
return std::filesystem::read_symlink(path);
|
||||||
|
} catch (std::filesystem::filesystem_error & e) {
|
||||||
|
throw SystemError(e.code(), "reading symbolic link '%s'", PathFmt(path));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Path readLink(const Path & path)
|
Path readLink(const Path & path)
|
||||||
@@ -336,23 +311,23 @@ void writeFile(const Path & path, std::string_view s, mode_t mode, FsSync sync)
|
|||||||
if (!fd)
|
if (!fd)
|
||||||
throw SysError("opening file '%1%'", path);
|
throw SysError("opening file '%1%'", path);
|
||||||
|
|
||||||
writeFile(fd, path, s, mode, sync);
|
writeFile(fd.get(), s, sync, &path);
|
||||||
|
|
||||||
/* Close explicitly to propagate the exceptions. */
|
/* Close explicitly to propagate the exceptions. */
|
||||||
fd.close();
|
fd.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
void writeFile(AutoCloseFD & fd, const Path & origPath, std::string_view s, mode_t mode, FsSync sync)
|
void writeFile(Descriptor fd, std::string_view s, FsSync sync, const Path * origPath)
|
||||||
{
|
{
|
||||||
assert(fd);
|
assert(fd != INVALID_DESCRIPTOR);
|
||||||
try {
|
try {
|
||||||
writeFull(fd.get(), s);
|
writeFull(fd, s);
|
||||||
|
|
||||||
if (sync == FsSync::Yes)
|
if (sync == FsSync::Yes)
|
||||||
fd.fsync();
|
syncDescriptor(fd);
|
||||||
|
|
||||||
} catch (Error & e) {
|
} catch (Error & e) {
|
||||||
e.addTrace({}, "writing file '%1%'", origPath);
|
e.addTrace({}, "writing file '%1%'", origPath ? *origPath : descriptorToPath(fd).string());
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -463,7 +438,7 @@ void createDirs(const std::filesystem::path & path)
|
|||||||
try {
|
try {
|
||||||
std::filesystem::create_directories(path);
|
std::filesystem::create_directories(path);
|
||||||
} catch (std::filesystem::filesystem_error & e) {
|
} catch (std::filesystem::filesystem_error & e) {
|
||||||
throw SysError("creating directory '%1%'", path.string());
|
throw SystemError(e.code(), "creating directory '%1%'", path.string());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -664,7 +639,7 @@ void replaceSymlink(const std::filesystem::path & target, const std::filesystem:
|
|||||||
} catch (std::filesystem::filesystem_error & e) {
|
} catch (std::filesystem::filesystem_error & e) {
|
||||||
if (e.code() == std::errc::file_exists)
|
if (e.code() == std::errc::file_exists)
|
||||||
continue;
|
continue;
|
||||||
throw SysError("creating symlink %1% -> %2%", PathFmt(tmp), PathFmt(target));
|
throw SystemError(e.code(), "creating symlink %1% -> %2%", PathFmt(tmp), PathFmt(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -672,7 +647,7 @@ void replaceSymlink(const std::filesystem::path & target, const std::filesystem:
|
|||||||
} catch (std::filesystem::filesystem_error & e) {
|
} catch (std::filesystem::filesystem_error & e) {
|
||||||
if (e.code() == std::errc::file_exists)
|
if (e.code() == std::errc::file_exists)
|
||||||
continue;
|
continue;
|
||||||
throw SysError("renaming %1% to %2%", PathFmt(tmp), PathFmt(link));
|
throw SystemError(e.code(), "renaming %1% to %2%", PathFmt(tmp), PathFmt(link));
|
||||||
}
|
}
|
||||||
|
|
||||||
break;
|
break;
|
||||||
@@ -773,7 +748,7 @@ std::filesystem::path makeParentCanonical(const std::filesystem::path & rawPath)
|
|||||||
}
|
}
|
||||||
return std::filesystem::canonical(parent) / path.filename();
|
return std::filesystem::canonical(parent) / path.filename();
|
||||||
} catch (std::filesystem::filesystem_error & e) {
|
} catch (std::filesystem::filesystem_error & e) {
|
||||||
throw SysError("canonicalising parent path of %1%", PathFmt(path));
|
throw SystemError(e.code(), "canonicalising parent path of %1%", PathFmt(path));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+28
-36
@@ -105,34 +105,26 @@ void RestoreSink::createDirectory(const CanonPath & path)
|
|||||||
{
|
{
|
||||||
auto p = append(dstPath, path);
|
auto p = append(dstPath, path);
|
||||||
|
|
||||||
#ifndef _WIN32
|
|
||||||
if (dirFd) {
|
if (dirFd) {
|
||||||
if (path.isRoot())
|
if (path.isRoot())
|
||||||
/* Trying to create a directory that we already have a file descriptor for. */
|
/* Trying to create a directory that we already have a file descriptor for. */
|
||||||
throw Error("path %s already exists", PathFmt(p));
|
throw Error("path %s already exists", PathFmt(p));
|
||||||
|
|
||||||
if (::mkdirat(dirFd.get(), path.rel_c_str(), 0777) == -1)
|
createDirectoryAt(dirFd.get(), path);
|
||||||
throw SysError("creating directory %s", PathFmt(p));
|
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
#endif
|
|
||||||
|
|
||||||
if (!std::filesystem::create_directory(p))
|
if (!std::filesystem::create_directory(p))
|
||||||
throw Error("path '%s' already exists", p.string());
|
throw Error("path '%s' already exists", p.string());
|
||||||
|
|
||||||
#ifndef _WIN32
|
|
||||||
if (path.isRoot()) {
|
if (path.isRoot()) {
|
||||||
assert(!dirFd); // Handled above
|
assert(!dirFd); // Handled above
|
||||||
|
|
||||||
/* Open directory for further *at operations relative to the sink root
|
/* Open directory for further *at operations relative to the sink root
|
||||||
directory. */
|
directory. */
|
||||||
dirFd = open(p.c_str(), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
|
dirFd = openDirectory(p, /*followFinalSymlink=*/false);
|
||||||
if (!dirFd)
|
|
||||||
throw SysError("creating directory %1%", PathFmt(p));
|
|
||||||
}
|
}
|
||||||
#endif
|
}
|
||||||
};
|
|
||||||
|
|
||||||
struct RestoreRegularFile : CreateRegularFileSink, FdSink
|
struct RestoreRegularFile : CreateRegularFileSink, FdSink
|
||||||
{
|
{
|
||||||
@@ -164,28 +156,26 @@ void RestoreSink::createRegularFile(const CanonPath & path, std::function<void(C
|
|||||||
{
|
{
|
||||||
auto p = append(dstPath, path);
|
auto p = append(dstPath, path);
|
||||||
|
|
||||||
auto crf = RestoreRegularFile(
|
auto crf = RestoreRegularFile(startFsync, [&]() -> Descriptor {
|
||||||
startFsync,
|
AutoCloseFD parentFd;
|
||||||
|
if (!dirFd) {
|
||||||
|
assert(path.isRoot());
|
||||||
|
assert(p.has_parent_path());
|
||||||
|
parentFd = openDirectory(p.parent_path());
|
||||||
|
}
|
||||||
|
return openFileEnsureBeneathNoSymlinks(
|
||||||
|
dirFd ? dirFd.get() : parentFd.get(),
|
||||||
|
dirFd ? path : CanonPath::root / p.filename().string(),
|
||||||
#ifdef _WIN32
|
#ifdef _WIN32
|
||||||
CreateFileW(
|
|
||||||
p.c_str(),
|
|
||||||
GENERIC_READ | GENERIC_WRITE,
|
GENERIC_READ | GENERIC_WRITE,
|
||||||
FILE_SHARE_READ | FILE_SHARE_WRITE,
|
FILE_NON_DIRECTORY_FILE,
|
||||||
NULL,
|
FILE_CREATE
|
||||||
CREATE_NEW,
|
|
||||||
FILE_ATTRIBUTE_NORMAL,
|
|
||||||
NULL)
|
|
||||||
#else
|
#else
|
||||||
[&]() {
|
O_CREAT | O_EXCL | O_WRONLY | O_CLOEXEC,
|
||||||
/* O_EXCL together with O_CREAT ensures symbolic links in the last
|
0666
|
||||||
component are not followed. */
|
|
||||||
constexpr int flags = O_CREAT | O_EXCL | O_WRONLY | O_CLOEXEC;
|
|
||||||
if (!dirFd)
|
|
||||||
return ::open(p.c_str(), flags, 0666);
|
|
||||||
return openFileEnsureBeneathNoSymlinks(dirFd.get(), path, flags, 0666);
|
|
||||||
}()
|
|
||||||
#endif
|
#endif
|
||||||
);
|
);
|
||||||
|
}());
|
||||||
if (!crf.fd)
|
if (!crf.fd)
|
||||||
throw NativeSysError("creating file %1%", PathFmt(p));
|
throw NativeSysError("creating file %1%", PathFmt(p));
|
||||||
func(crf);
|
func(crf);
|
||||||
@@ -224,14 +214,16 @@ void RestoreRegularFile::preallocateContents(uint64_t len)
|
|||||||
void RestoreSink::createSymlink(const CanonPath & path, const std::string & target)
|
void RestoreSink::createSymlink(const CanonPath & path, const std::string & target)
|
||||||
{
|
{
|
||||||
auto p = append(dstPath, path);
|
auto p = append(dstPath, path);
|
||||||
#ifndef _WIN32
|
AutoCloseFD parentFd;
|
||||||
if (dirFd) {
|
if (!dirFd) {
|
||||||
if (::symlinkat(requireCString(target), dirFd.get(), path.rel_c_str()) == -1)
|
assert(path.isRoot());
|
||||||
throw SysError("creating symlink from %1% -> '%2%'", PathFmt(p), target);
|
assert(p.has_parent_path());
|
||||||
return;
|
parentFd = openDirectory(p.parent_path());
|
||||||
}
|
}
|
||||||
#endif
|
createUnknownSymlinkAt(
|
||||||
nix::createSymlink(target, p.string());
|
dirFd ? dirFd.get() : parentFd.get(),
|
||||||
|
dirFd ? path : CanonPath::root / p.filename().string(),
|
||||||
|
string_to_os_string(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
void RegularFileSink::createRegularFile(const CanonPath & path, std::function<void(CreateRegularFileSink &)> func)
|
void RegularFileSink::createRegularFile(const CanonPath & path, std::function<void(CreateRegularFileSink &)> func)
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
#pragma once
|
||||||
|
/// @file
|
||||||
|
|
||||||
|
#include "nix/util/source-accessor.hh"
|
||||||
|
#include "nix/util/ref.hh"
|
||||||
|
|
||||||
|
#include <filesystem>
|
||||||
|
|
||||||
|
namespace nix {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a directory accessor rooted at @param root.
|
||||||
|
*
|
||||||
|
* On unix accesses are performed with openat. Linux uses openat2 if supported
|
||||||
|
* by the kernel (>= 5.6).
|
||||||
|
*
|
||||||
|
* On Windows returns a PosixSourceAccessor.
|
||||||
|
*
|
||||||
|
* @param fd Descriptor of the directory.
|
||||||
|
* @param root Filesystem path corresponding to fd. Must correspond to a directory.
|
||||||
|
*/
|
||||||
|
ref<SourceAccessor>
|
||||||
|
makeDirectorySourceAccessor(AutoCloseFD fd, std::filesystem::path root, bool trackLastModified = false);
|
||||||
|
|
||||||
|
} // namespace nix
|
||||||
@@ -17,6 +17,7 @@
|
|||||||
|
|
||||||
#include "nix/util/suggestions.hh"
|
#include "nix/util/suggestions.hh"
|
||||||
#include "nix/util/fmt.hh"
|
#include "nix/util/fmt.hh"
|
||||||
|
#include "nix/util/config.hh"
|
||||||
|
|
||||||
#include <cstring>
|
#include <cstring>
|
||||||
#include <list>
|
#include <list>
|
||||||
@@ -126,20 +127,20 @@ public:
|
|||||||
BaseError & operator=(BaseError &&) = default;
|
BaseError & operator=(BaseError &&) = default;
|
||||||
|
|
||||||
template<typename... Args>
|
template<typename... Args>
|
||||||
BaseError(unsigned int status, const Args &... args)
|
BaseError(unsigned int status, Args &&... args)
|
||||||
: err{.level = lvlError, .msg = HintFmt(args...), .pos = {}, .status = status}
|
: err{.level = lvlError, .msg = HintFmt(std::forward<Args>(args)...), .pos = {}, .status = status}
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
template<typename... Args>
|
template<typename... Args>
|
||||||
explicit BaseError(const std::string & fs, const Args &... args)
|
explicit BaseError(const std::string & fs, Args &&... args)
|
||||||
: err{.level = lvlError, .msg = HintFmt(fs, args...), .pos = {}}
|
: err{.level = lvlError, .msg = HintFmt(fs, std::forward<Args>(args)...), .pos = {}}
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
template<typename... Args>
|
template<typename... Args>
|
||||||
BaseError(const Suggestions & sug, const Args &... args)
|
BaseError(const Suggestions & sug, Args &&... args)
|
||||||
: err{.level = lvlError, .msg = HintFmt(args...), .pos = {}, .suggestions = sug}
|
: err{.level = lvlError, .msg = HintFmt(std::forward<Args>(args)...), .pos = {}, .suggestions = sug}
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -203,9 +204,9 @@ public:
|
|||||||
* @param args... Format string arguments.
|
* @param args... Format string arguments.
|
||||||
*/
|
*/
|
||||||
template<typename... Args>
|
template<typename... Args>
|
||||||
void addTrace(std::shared_ptr<const Pos> && pos, std::string_view fs, const Args &... args)
|
void addTrace(std::shared_ptr<const Pos> && pos, std::string_view fs, Args &&... args)
|
||||||
{
|
{
|
||||||
addTrace(std::move(pos), HintFmt(std::string(fs), args...));
|
addTrace(std::move(pos), HintFmt(std::string(fs), std::forward<Args>(args)...));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -226,31 +227,13 @@ public:
|
|||||||
{
|
{
|
||||||
return err;
|
return err;
|
||||||
};
|
};
|
||||||
|
|
||||||
[[noreturn]] virtual void throwClone() const = 0;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
template<typename Derived, typename Base>
|
#define MakeError(newClass, superClass) \
|
||||||
class CloneableError : public Base
|
class newClass : public superClass \
|
||||||
{
|
{ \
|
||||||
public:
|
public: \
|
||||||
using Base::Base;
|
using superClass::superClass; \
|
||||||
|
|
||||||
/**
|
|
||||||
* Rethrow a copy of this exception. Useful when the exception can get
|
|
||||||
* modified when appending traces.
|
|
||||||
*/
|
|
||||||
[[noreturn]] void throwClone() const override
|
|
||||||
{
|
|
||||||
throw Derived(static_cast<const Derived &>(*this));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
#define MakeError(newClass, superClass) \
|
|
||||||
class newClass : public CloneableError<newClass, superClass> \
|
|
||||||
{ \
|
|
||||||
public: \
|
|
||||||
using CloneableError<newClass, superClass>::CloneableError; \
|
|
||||||
}
|
}
|
||||||
|
|
||||||
MakeError(Error, BaseError);
|
MakeError(Error, BaseError);
|
||||||
@@ -262,22 +245,42 @@ MakeError(UnimplementedError, Error);
|
|||||||
* std::error_code. Use when you want to catch and check an error condition like
|
* std::error_code. Use when you want to catch and check an error condition like
|
||||||
* no_such_file_or_directory (ENOENT) without ifdefs.
|
* no_such_file_or_directory (ENOENT) without ifdefs.
|
||||||
*/
|
*/
|
||||||
class SystemError : public CloneableError<SystemError, Error>
|
class SystemError : public Error
|
||||||
{
|
{
|
||||||
std::error_code errorCode;
|
std::error_code errorCode;
|
||||||
|
std::string errorDetails;
|
||||||
|
|
||||||
public:
|
protected:
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Just here to allow derived classes to use the right constructor
|
||||||
|
* (the protected one).
|
||||||
|
*/
|
||||||
|
struct Disambig
|
||||||
|
{};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Protected constructor for subclasses that provide their own error message.
|
||||||
|
* The error message is appended to the formatted hint.
|
||||||
|
*/
|
||||||
template<typename... Args>
|
template<typename... Args>
|
||||||
SystemError(std::errc posixErrNo, Args &&... args)
|
SystemError(Disambig, std::error_code errorCode, std::string_view errorDetails, Args &&... args)
|
||||||
: CloneableError(std::forward<Args>(args)...)
|
: Error("")
|
||||||
, errorCode(std::make_error_code(posixErrNo))
|
, errorCode(errorCode)
|
||||||
|
, errorDetails(errorDetails)
|
||||||
{
|
{
|
||||||
|
auto hf = HintFmt(std::forward<Args>(args)...);
|
||||||
|
err.msg = HintFmt("%s: %s", Uncolored(hf.str()), errorDetails);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public:
|
||||||
|
/**
|
||||||
|
* Construct with an error code. The error code's message is automatically
|
||||||
|
* appended to the error message.
|
||||||
|
*/
|
||||||
template<typename... Args>
|
template<typename... Args>
|
||||||
SystemError(std::error_code errorCode, Args &&... args)
|
SystemError(std::error_code errorCode, Args &&... args)
|
||||||
: CloneableError(std::forward<Args>(args)...)
|
: SystemError(Disambig{}, errorCode, errorCode.message(), std::forward<Args>(args)...)
|
||||||
, errorCode(errorCode)
|
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -308,7 +311,7 @@ public:
|
|||||||
* support is too WIP to justify the code churn, but if it is finished
|
* support is too WIP to justify the code churn, but if it is finished
|
||||||
* then a better identifier becomes moe worth it.
|
* then a better identifier becomes moe worth it.
|
||||||
*/
|
*/
|
||||||
class SysError final : public CloneableError<SysError, SystemError>
|
class SysError : public SystemError
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
int errNo;
|
int errNo;
|
||||||
@@ -318,12 +321,14 @@ public:
|
|||||||
* will be used to try to add additional information to the message.
|
* will be used to try to add additional information to the message.
|
||||||
*/
|
*/
|
||||||
template<typename... Args>
|
template<typename... Args>
|
||||||
SysError(int errNo, const Args &... args)
|
SysError(int errNo, Args &&... args)
|
||||||
: CloneableError(static_cast<std::errc>(errNo), "")
|
: SystemError(
|
||||||
|
Disambig{},
|
||||||
|
std::make_error_code(static_cast<std::errc>(errNo)),
|
||||||
|
strerror(errNo),
|
||||||
|
std::forward<Args>(args)...)
|
||||||
, errNo(errNo)
|
, errNo(errNo)
|
||||||
{
|
{
|
||||||
auto hf = HintFmt(args...);
|
|
||||||
err.msg = HintFmt("%1%: %2%", Uncolored(hf.str()), strerror(errNo));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -333,8 +338,8 @@ public:
|
|||||||
* calling this constructor!
|
* calling this constructor!
|
||||||
*/
|
*/
|
||||||
template<typename... Args>
|
template<typename... Args>
|
||||||
SysError(const Args &... args)
|
SysError(Args &&... args)
|
||||||
: SysError(errno, args...)
|
: SysError(errno, std::forward<Args>(args)...)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -368,7 +373,7 @@ int handleExceptions(const std::string & programName, std::function<void()> fun)
|
|||||||
*/
|
*/
|
||||||
[[gnu::noinline, gnu::cold, noreturn]] void unreachable(std::source_location loc = std::source_location::current());
|
[[gnu::noinline, gnu::cold, noreturn]] void unreachable(std::source_location loc = std::source_location::current());
|
||||||
|
|
||||||
#if NIX_UBSAN_ENABLED == 1
|
#if NIX_UBSAN_ENABLED
|
||||||
/* When building with sanitizers, also enable expensive unreachable checks. In
|
/* When building with sanitizers, also enable expensive unreachable checks. In
|
||||||
optimised builds this explicitly invokes UB with std::unreachable for better
|
optimised builds this explicitly invokes UB with std::unreachable for better
|
||||||
optimisations. */
|
optimisations. */
|
||||||
@@ -387,7 +392,7 @@ namespace windows {
|
|||||||
* Unless you need to catch a specific error number, don't catch this in
|
* Unless you need to catch a specific error number, don't catch this in
|
||||||
* portable code. Catch `SystemError` instead.
|
* portable code. Catch `SystemError` instead.
|
||||||
*/
|
*/
|
||||||
class WinError : public CloneableError<WinError, SystemError>
|
class WinError : public SystemError
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
DWORD lastError;
|
DWORD lastError;
|
||||||
@@ -398,12 +403,14 @@ public:
|
|||||||
* information to the message.
|
* information to the message.
|
||||||
*/
|
*/
|
||||||
template<typename... Args>
|
template<typename... Args>
|
||||||
WinError(DWORD lastError, const Args &... args)
|
WinError(DWORD lastError, Args &&... args)
|
||||||
: CloneableError(std::error_code(lastError, std::system_category()), "")
|
: SystemError(
|
||||||
|
Disambig{},
|
||||||
|
std::error_code(lastError, std::system_category()),
|
||||||
|
renderError(lastError),
|
||||||
|
std::forward<Args>(args)...)
|
||||||
, lastError(lastError)
|
, lastError(lastError)
|
||||||
{
|
{
|
||||||
auto hf = HintFmt(args...);
|
|
||||||
err.msg = HintFmt("%1%: %2%", Uncolored(hf.str()), renderError(lastError));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -413,14 +420,14 @@ public:
|
|||||||
* before calling this constructor!
|
* before calling this constructor!
|
||||||
*/
|
*/
|
||||||
template<typename... Args>
|
template<typename... Args>
|
||||||
WinError(const Args &... args)
|
WinError(Args &&... args)
|
||||||
: WinError(GetLastError(), args...)
|
: WinError(GetLastError(), std::forward<Args>(args)...)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|
||||||
std::string renderError(DWORD lastError);
|
static std::string renderError(DWORD lastError);
|
||||||
};
|
};
|
||||||
|
|
||||||
} // namespace windows
|
} // namespace windows
|
||||||
|
|||||||
@@ -80,7 +80,7 @@ std::set<ExperimentalFeature> parseFeatures(const StringSet &);
|
|||||||
* An experimental feature was required for some (experimental)
|
* An experimental feature was required for some (experimental)
|
||||||
* operation, but was not enabled.
|
* operation, but was not enabled.
|
||||||
*/
|
*/
|
||||||
class MissingExperimentalFeature final : public CloneableError<MissingExperimentalFeature, Error>
|
class MissingExperimentalFeature : public Error
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -133,6 +133,11 @@ std::string readLine(Descriptor fd, bool eofOk = false, char terminator = '\n');
|
|||||||
*/
|
*/
|
||||||
void writeLine(Descriptor fd, std::string s);
|
void writeLine(Descriptor fd, std::string s);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Perform a blocking fsync operation on a file descriptor.
|
||||||
|
*/
|
||||||
|
void syncDescriptor(Descriptor fd);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Options for draining a file descriptor to a sink.
|
* Options for draining a file descriptor to a sink.
|
||||||
*/
|
*/
|
||||||
@@ -253,7 +258,11 @@ public:
|
|||||||
/**
|
/**
|
||||||
* Perform a blocking fsync operation.
|
* Perform a blocking fsync operation.
|
||||||
*/
|
*/
|
||||||
void fsync() const;
|
void fsync() const
|
||||||
|
{
|
||||||
|
if (fd != INVALID_DESCRIPTOR)
|
||||||
|
nix::syncDescriptor(fd);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Asynchronously flush to disk without blocking, if available on
|
* Asynchronously flush to disk without blocking, if available on
|
||||||
|
|||||||
@@ -15,6 +15,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
#include "nix/util/file-descriptor.hh"
|
#include "nix/util/file-descriptor.hh"
|
||||||
|
#include "nix/util/file-system.hh"
|
||||||
|
|
||||||
#include <optional>
|
#include <optional>
|
||||||
|
|
||||||
@@ -33,6 +34,90 @@ namespace nix {
|
|||||||
*/
|
*/
|
||||||
OsString readLinkAt(Descriptor dirFd, const CanonPath & path);
|
OsString readLinkAt(Descriptor dirFd, const CanonPath & path);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a symlink to a file relative to a directory file descriptor.
|
||||||
|
*
|
||||||
|
* On Windows, creates a file symlink. On Unix, equivalent to symlinkat.
|
||||||
|
*
|
||||||
|
* @param dirFd Directory file descriptor
|
||||||
|
* @param path Relative path for the new symlink
|
||||||
|
* @param target The symlink target (what it points to)
|
||||||
|
*
|
||||||
|
* @throws SystemError on any I/O errors.
|
||||||
|
*/
|
||||||
|
void createFileSymlinkAt(Descriptor dirFd, const CanonPath & path, const OsString & target);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a symlink to a directory relative to a directory file descriptor.
|
||||||
|
*
|
||||||
|
* On Windows, creates a directory symlink. On Unix, equivalent to symlinkat.
|
||||||
|
*
|
||||||
|
* @param dirFd Directory file descriptor
|
||||||
|
* @param path Relative path for the new symlink
|
||||||
|
* @param target The symlink target (what it points to)
|
||||||
|
*
|
||||||
|
* @throws SystemError on any I/O errors.
|
||||||
|
*/
|
||||||
|
void createDirectorySymlinkAt(Descriptor dirFd, const CanonPath & path, const OsString & target);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a symlink relative to a directory file descriptor, detecting target type.
|
||||||
|
*
|
||||||
|
* On Windows, stats the target to determine whether to create a file or
|
||||||
|
* directory symlink. Falls back to file symlink if the target does not exist.
|
||||||
|
* On Unix, equivalent to symlinkat.
|
||||||
|
*
|
||||||
|
* @param dirFd Directory file descriptor
|
||||||
|
* @param path Relative path for the new symlink
|
||||||
|
* @param target The symlink target (what it points to)
|
||||||
|
*
|
||||||
|
* @throws SystemError on any I/O errors.
|
||||||
|
*/
|
||||||
|
void createUnknownSymlinkAt(Descriptor dirFd, const CanonPath & path, const OsString & target);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a directory relative to a directory file descriptor.
|
||||||
|
*
|
||||||
|
* @param dirFd Directory file descriptor
|
||||||
|
* @param path Relative path for the new directory
|
||||||
|
*
|
||||||
|
* @throws SystemError on any I/O errors.
|
||||||
|
*/
|
||||||
|
void createDirectoryAt(Descriptor dirFd, const CanonPath & path);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get status of an open file/directory handle.
|
||||||
|
*
|
||||||
|
* @param fd File descriptor/handle
|
||||||
|
* @throws SystemError on I/O errors.
|
||||||
|
*/
|
||||||
|
PosixStat fstat(Descriptor fd);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get status of a file relative to a directory file descriptor.
|
||||||
|
*
|
||||||
|
* @param dirFd Directory file descriptor
|
||||||
|
* @param path Relative path to stat
|
||||||
|
*
|
||||||
|
* @return nullopt if the path does not exist.
|
||||||
|
* @throws SystemError on other I/O errors.
|
||||||
|
*
|
||||||
|
* @pre path.isRoot() is false
|
||||||
|
*/
|
||||||
|
std::optional<PosixStat> maybeFstatat(Descriptor dirFd, const CanonPath & path);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get status of a file relative to a directory file descriptor.
|
||||||
|
*
|
||||||
|
* @param dirFd Directory file descriptor
|
||||||
|
* @param path Relative path to stat
|
||||||
|
*
|
||||||
|
* @throws SystemError if the path does not exist or on other I/O errors.
|
||||||
|
*
|
||||||
|
* @pre path.isRoot() is false
|
||||||
|
*/
|
||||||
|
PosixStat fstatat(Descriptor dirFd, const CanonPath & path);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Safe(r) function to open a file relative to dirFd, while
|
* Safe(r) function to open a file relative to dirFd, while
|
||||||
* disallowing escaping from a directory and any symlinks in the process.
|
* disallowing escaping from a directory and any symlinks in the process.
|
||||||
@@ -75,7 +160,7 @@ namespace linux {
|
|||||||
*
|
*
|
||||||
* @see https://man7.org/linux/man-pages/man2/openat2.2.html
|
* @see https://man7.org/linux/man-pages/man2/openat2.2.html
|
||||||
* @see https://man7.org/linux/man-pages/man2/open_how.2type.html
|
* @see https://man7.org/linux/man-pages/man2/open_how.2type.html
|
||||||
v*
|
*
|
||||||
* @param flags O_* flags
|
* @param flags O_* flags
|
||||||
* @param mode Mode for O_{CREAT,TMPFILE}
|
* @param mode Mode for O_{CREAT,TMPFILE}
|
||||||
* @param resolve RESOLVE_* flags
|
* @param resolve RESOLVE_* flags
|
||||||
|
|||||||
@@ -28,11 +28,20 @@
|
|||||||
* Polyfill for MinGW
|
* Polyfill for MinGW
|
||||||
*
|
*
|
||||||
* Windows does in fact support symlinks, but the C runtime interfaces predate this.
|
* Windows does in fact support symlinks, but the C runtime interfaces predate this.
|
||||||
*
|
* We define S_IFLNK and S_ISLNK so that our lstat implementation can properly
|
||||||
* @todo get rid of this, and stop using `stat` when we want `lstat` too.
|
* indicate symlinks by setting these mode bits when it detects a reparse point.
|
||||||
*/
|
*/
|
||||||
|
#ifndef S_IFLNK
|
||||||
|
# ifndef _WIN32
|
||||||
|
# error "S_IFLNK should be defined on non-Windows platforms"
|
||||||
|
# endif
|
||||||
|
# define S_IFLNK 0120000
|
||||||
|
#endif
|
||||||
#ifndef S_ISLNK
|
#ifndef S_ISLNK
|
||||||
# define S_ISLNK(m) false
|
# ifndef _WIN32
|
||||||
|
# error "S_ISLNK should be defined on non-Windows platforms"
|
||||||
|
# endif
|
||||||
|
# define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
namespace nix {
|
namespace nix {
|
||||||
@@ -125,6 +134,38 @@ using PosixStat =
|
|||||||
#endif
|
#endif
|
||||||
;
|
;
|
||||||
|
|
||||||
|
#ifdef _WIN32
|
||||||
|
namespace windows {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert Windows FILETIME to Unix time_t.
|
||||||
|
*/
|
||||||
|
time_t fileTimeToUnixTime(const FILETIME & ft);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fill a PosixStat structure from file attributes and timestamps.
|
||||||
|
*
|
||||||
|
* @param dwFileAttributes File attributes (FILE_ATTRIBUTE_*)
|
||||||
|
* @param ftCreationTime Creation time
|
||||||
|
* @param ftLastAccessTime Last access time
|
||||||
|
* @param ftLastWriteTime Last write time
|
||||||
|
* @param nFileSizeHigh High 32 bits of file size
|
||||||
|
* @param nFileSizeLow Low 32 bits of file size
|
||||||
|
* @param nNumberOfLinks Number of hard links (default 1)
|
||||||
|
*/
|
||||||
|
void statFromFileInfo(
|
||||||
|
PosixStat & st,
|
||||||
|
DWORD dwFileAttributes,
|
||||||
|
const FILETIME & ftCreationTime,
|
||||||
|
const FILETIME & ftLastAccessTime,
|
||||||
|
const FILETIME & ftLastWriteTime,
|
||||||
|
DWORD nFileSizeHigh,
|
||||||
|
DWORD nFileSizeLow,
|
||||||
|
DWORD nNumberOfLinks = 1);
|
||||||
|
|
||||||
|
} // namespace windows
|
||||||
|
#endif
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get status of `path`.
|
* Get status of `path`.
|
||||||
*/
|
*/
|
||||||
@@ -133,10 +174,6 @@ PosixStat lstat(const std::filesystem::path & path);
|
|||||||
* Get status of `path` following symlinks.
|
* Get status of `path` following symlinks.
|
||||||
*/
|
*/
|
||||||
PosixStat stat(const std::filesystem::path & path);
|
PosixStat stat(const std::filesystem::path & path);
|
||||||
/**
|
|
||||||
* Get status of an open file descriptor.
|
|
||||||
*/
|
|
||||||
PosixStat fstat(int fd);
|
|
||||||
/**
|
/**
|
||||||
* `lstat` the given path if it exists.
|
* `lstat` the given path if it exists.
|
||||||
* @return std::nullopt if the path doesn't exist, or an optional containing the result of `lstat` otherwise
|
* @return std::nullopt if the path doesn't exist, or an optional containing the result of `lstat` otherwise
|
||||||
@@ -189,26 +226,26 @@ Path readLink(const Path & path);
|
|||||||
*/
|
*/
|
||||||
std::filesystem::path readLink(const std::filesystem::path & path);
|
std::filesystem::path readLink(const std::filesystem::path & path);
|
||||||
|
|
||||||
#ifdef _WIN32
|
|
||||||
namespace windows {
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the path associated with a file handle.
|
* Get the path associated with a file descriptor.
|
||||||
*
|
*
|
||||||
* @note One MUST only use this for error handling, because it creates
|
* @note One MUST only use this for error handling, because it creates
|
||||||
* TOCTOU issues. We don't mind if error messages point to out of date
|
* TOCTOU issues. We don't mind if error messages point to out of date
|
||||||
* paths (that is a rather trivial TOCTOU --- the error message is best
|
* paths (that is a rather trivial TOCTOU --- the error message is best
|
||||||
* effort) but for anything else we do.
|
* effort) but for anything else we do.
|
||||||
|
*
|
||||||
|
* @note this function will clobber `errno` (Unix) / "last error"
|
||||||
|
* (Windows), so care must be used to get those error codes, then call
|
||||||
|
* this, then build a `SysError` / `WinError` with the saved error code.
|
||||||
*/
|
*/
|
||||||
std::filesystem::path handleToPath(Descriptor handle);
|
std::filesystem::path descriptorToPath(Descriptor fd);
|
||||||
|
|
||||||
} // namespace windows
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Open a `Descriptor` with read-only access to the given directory.
|
* Open a `Descriptor` with read-only access to the given directory.
|
||||||
|
*
|
||||||
|
* @param followSymlinks If false, fail if the path is a symlink.
|
||||||
*/
|
*/
|
||||||
Descriptor openDirectory(const std::filesystem::path & path);
|
Descriptor openDirectory(const std::filesystem::path & path, bool followFinalSymlink = true);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Open a `Descriptor` with read-only access to the given file.
|
* Open a `Descriptor` with read-only access to the given file.
|
||||||
@@ -268,8 +305,7 @@ writeFile(const std::filesystem::path & path, Source & source, mode_t mode = 066
|
|||||||
return writeFile(path.string(), source, mode, sync);
|
return writeFile(path.string(), source, mode, sync);
|
||||||
}
|
}
|
||||||
|
|
||||||
void writeFile(
|
void writeFile(Descriptor fd, std::string_view s, FsSync sync = FsSync::No, const Path * origPath = nullptr);
|
||||||
AutoCloseFD & fd, const Path & origPath, std::string_view s, mode_t mode = 0666, FsSync sync = FsSync::No);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Flush a path's parent directory to disk.
|
* Flush a path's parent directory to disk.
|
||||||
|
|||||||
@@ -2,7 +2,12 @@
|
|||||||
|
|
||||||
include_dirs = [ include_directories('../..') ]
|
include_dirs = [ include_directories('../..') ]
|
||||||
|
|
||||||
headers = files(
|
config_pub_h = configure_file(
|
||||||
|
configuration : configdata_pub,
|
||||||
|
output : 'config.hh',
|
||||||
|
)
|
||||||
|
|
||||||
|
headers = [ config_pub_h ] + files(
|
||||||
'abstract-setting-to-json.hh',
|
'abstract-setting-to-json.hh',
|
||||||
'alignment.hh',
|
'alignment.hh',
|
||||||
'ansicolor.hh',
|
'ansicolor.hh',
|
||||||
@@ -27,6 +32,7 @@ headers = files(
|
|||||||
'configuration.hh',
|
'configuration.hh',
|
||||||
'current-process.hh',
|
'current-process.hh',
|
||||||
'demangle.hh',
|
'demangle.hh',
|
||||||
|
'directory-source-accessor.hh',
|
||||||
'english.hh',
|
'english.hh',
|
||||||
'environment-variables.hh',
|
'environment-variables.hh',
|
||||||
'error.hh',
|
'error.hh',
|
||||||
|
|||||||
@@ -82,6 +82,8 @@ public:
|
|||||||
|
|
||||||
void invalidateCache(const CanonPath & path) override;
|
void invalidateCache(const CanonPath & path) override;
|
||||||
|
|
||||||
|
static Stat makeStat(const struct ::stat st);
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -133,14 +133,14 @@ std::pair<int, std::string> runProgram(RunOptions && options);
|
|||||||
|
|
||||||
void runProgram2(const RunOptions & options);
|
void runProgram2(const RunOptions & options);
|
||||||
|
|
||||||
class ExecError final : public CloneableError<ExecError, Error>
|
class ExecError : public Error
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
int status;
|
int status;
|
||||||
|
|
||||||
template<typename... Args>
|
template<typename... Args>
|
||||||
ExecError(int status, const Args &... args)
|
ExecError(int status, const Args &... args)
|
||||||
: CloneableError(args...)
|
: Error(args...)
|
||||||
, status(status)
|
, status(status)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -231,19 +231,19 @@ ref<SourceAccessor> makeEmptySourceAccessor();
|
|||||||
*/
|
*/
|
||||||
MakeError(RestrictedPathError, Error);
|
MakeError(RestrictedPathError, Error);
|
||||||
|
|
||||||
struct SymlinkNotAllowed final : public CloneableError<SymlinkNotAllowed, Error>
|
struct SymlinkNotAllowed : public Error
|
||||||
{
|
{
|
||||||
CanonPath path;
|
CanonPath path;
|
||||||
|
|
||||||
SymlinkNotAllowed(CanonPath path)
|
SymlinkNotAllowed(CanonPath path)
|
||||||
: CloneableError("relative path '%s' points to a symlink, which is not allowed", path.rel())
|
: Error("relative path '%s' points to a symlink, which is not allowed", path.rel())
|
||||||
, path(std::move(path))
|
, path(std::move(path))
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
template<typename... Args>
|
template<typename... Args>
|
||||||
SymlinkNotAllowed(CanonPath path, const std::string & fs, Args &&... args)
|
SymlinkNotAllowed(CanonPath path, const std::string & fs, Args &&... args)
|
||||||
: CloneableError(fs, std::forward<Args>(args)...)
|
: Error(fs, std::forward<Args>(args)...)
|
||||||
, path(std::move(path))
|
, path(std::move(path))
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|||||||
+13
-4
@@ -16,7 +16,8 @@ cxx = meson.get_compiler('cpp')
|
|||||||
|
|
||||||
subdir('nix-meson-build-support/deps-lists')
|
subdir('nix-meson-build-support/deps-lists')
|
||||||
|
|
||||||
configdata = configuration_data()
|
configdata_pub = configuration_data()
|
||||||
|
configdata_priv = configuration_data()
|
||||||
|
|
||||||
deps_private_maybe_subproject = []
|
deps_private_maybe_subproject = []
|
||||||
deps_public_maybe_subproject = []
|
deps_public_maybe_subproject = []
|
||||||
@@ -34,9 +35,15 @@ check_funcs = [
|
|||||||
foreach funcspec : check_funcs
|
foreach funcspec : check_funcs
|
||||||
define_name = 'HAVE_' + funcspec[0].underscorify().to_upper()
|
define_name = 'HAVE_' + funcspec[0].underscorify().to_upper()
|
||||||
define_value = cxx.has_function(funcspec[0]).to_int()
|
define_value = cxx.has_function(funcspec[0]).to_int()
|
||||||
configdata.set(define_name, define_value, description : funcspec[1])
|
configdata_priv.set(define_name, define_value, description : funcspec[1])
|
||||||
endforeach
|
endforeach
|
||||||
|
|
||||||
|
configdata_pub.set(
|
||||||
|
'NIX_UBSAN_ENABLED',
|
||||||
|
('undefined' in get_option('b_sanitize')).to_int(),
|
||||||
|
description : 'Whether nix has been built with UBSan enabled',
|
||||||
|
)
|
||||||
|
|
||||||
subdir('nix-meson-build-support/libatomic')
|
subdir('nix-meson-build-support/libatomic')
|
||||||
|
|
||||||
if host_machine.system() == 'windows'
|
if host_machine.system() == 'windows'
|
||||||
@@ -104,7 +111,7 @@ cpuid = dependency(
|
|||||||
version : '>= 0.7.0',
|
version : '>= 0.7.0',
|
||||||
required : cpuid_required,
|
required : cpuid_required,
|
||||||
)
|
)
|
||||||
configdata.set('HAVE_LIBCPUID', cpuid.found().to_int())
|
configdata_priv.set('HAVE_LIBCPUID', cpuid.found().to_int())
|
||||||
deps_private += cpuid
|
deps_private += cpuid
|
||||||
|
|
||||||
nlohmann_json = dependency('nlohmann_json', version : '>= 3.9')
|
nlohmann_json = dependency('nlohmann_json', version : '>= 3.9')
|
||||||
@@ -113,7 +120,7 @@ deps_public += nlohmann_json
|
|||||||
cxx = meson.get_compiler('cpp')
|
cxx = meson.get_compiler('cpp')
|
||||||
|
|
||||||
config_priv_h = configure_file(
|
config_priv_h = configure_file(
|
||||||
configuration : configdata,
|
configuration : configdata_priv,
|
||||||
output : 'util-config-private.hh',
|
output : 'util-config-private.hh',
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -132,6 +139,7 @@ sources = [ config_priv_h ] + files(
|
|||||||
'config-global.cc',
|
'config-global.cc',
|
||||||
'configuration.cc',
|
'configuration.cc',
|
||||||
'current-process.cc',
|
'current-process.cc',
|
||||||
|
'directory-source-accessor.cc',
|
||||||
'english.cc',
|
'english.cc',
|
||||||
'environment-variables.cc',
|
'environment-variables.cc',
|
||||||
'error.cc',
|
'error.cc',
|
||||||
@@ -140,6 +148,7 @@ sources = [ config_priv_h ] + files(
|
|||||||
'experimental-features.cc',
|
'experimental-features.cc',
|
||||||
'file-content-address.cc',
|
'file-content-address.cc',
|
||||||
'file-descriptor.cc',
|
'file-descriptor.cc',
|
||||||
|
'file-system-at.cc',
|
||||||
'file-system.cc',
|
'file-system.cc',
|
||||||
'fs-sink.cc',
|
'fs-sink.cc',
|
||||||
'git.cc',
|
'git.cc',
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
#include "nix/util/posix-source-accessor.hh"
|
#include "nix/util/posix-source-accessor.hh"
|
||||||
|
#include "nix/util/directory-source-accessor.hh"
|
||||||
#include "nix/util/source-path.hh"
|
#include "nix/util/source-path.hh"
|
||||||
#include "nix/util/signals.hh"
|
#include "nix/util/signals.hh"
|
||||||
#include "nix/util/sync.hh"
|
#include "nix/util/sync.hh"
|
||||||
@@ -108,22 +109,7 @@ std::optional<SourceAccessor::Stat> PosixSourceAccessor::maybeLstat(const CanonP
|
|||||||
if (trackLastModified)
|
if (trackLastModified)
|
||||||
mtime = std::max(mtime, st->st_mtime);
|
mtime = std::max(mtime, st->st_mtime);
|
||||||
|
|
||||||
return Stat{
|
return makeStat(*st);
|
||||||
.type = S_ISREG(st->st_mode) ? tRegular
|
|
||||||
: S_ISDIR(st->st_mode) ? tDirectory
|
|
||||||
: S_ISLNK(st->st_mode) ? tSymlink
|
|
||||||
: S_ISCHR(st->st_mode) ? tChar
|
|
||||||
: S_ISBLK(st->st_mode) ? tBlock
|
|
||||||
:
|
|
||||||
#ifdef S_ISSOCK
|
|
||||||
S_ISSOCK(st->st_mode) ? tSocket
|
|
||||||
:
|
|
||||||
#endif
|
|
||||||
S_ISFIFO(st->st_mode) ? tFifo
|
|
||||||
: tUnknown,
|
|
||||||
.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)
|
SourceAccessor::DirEntries PosixSourceAccessor::readDirectory(const CanonPath & path)
|
||||||
@@ -170,7 +156,7 @@ SourceAccessor::DirEntries PosixSourceAccessor::readDirectory(const CanonPath &
|
|||||||
if (e.code() == std::errc::permission_denied || e.code() == std::errc::operation_not_permitted)
|
if (e.code() == std::errc::permission_denied || e.code() == std::errc::operation_not_permitted)
|
||||||
return std::nullopt;
|
return std::nullopt;
|
||||||
else
|
else
|
||||||
throw;
|
throw SystemError(e.code(), "getting status of '%s'", PathFmt(entry.path()));
|
||||||
}
|
}
|
||||||
}();
|
}();
|
||||||
res.emplace(entry.path().filename().string(), type);
|
res.emplace(entry.path().filename().string(), type);
|
||||||
@@ -200,6 +186,26 @@ void PosixSourceAccessor::assertNoSymlinks(CanonPath path)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
PosixSourceAccessor::Stat PosixSourceAccessor::makeStat(const struct ::stat st)
|
||||||
|
{
|
||||||
|
return Stat{
|
||||||
|
.type = S_ISREG(st.st_mode) ? tRegular
|
||||||
|
: S_ISDIR(st.st_mode) ? tDirectory
|
||||||
|
: S_ISLNK(st.st_mode) ? tSymlink
|
||||||
|
: S_ISCHR(st.st_mode) ? tChar
|
||||||
|
: S_ISBLK(st.st_mode) ? tBlock
|
||||||
|
:
|
||||||
|
#ifdef S_ISSOCK
|
||||||
|
S_ISSOCK(st.st_mode) ? tSocket
|
||||||
|
:
|
||||||
|
#endif
|
||||||
|
S_ISFIFO(st.st_mode) ? tFifo
|
||||||
|
: tUnknown,
|
||||||
|
.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,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
ref<SourceAccessor> getFSSourceAccessor()
|
ref<SourceAccessor> getFSSourceAccessor()
|
||||||
{
|
{
|
||||||
static auto rootFS = make_ref<PosixSourceAccessor>();
|
static auto rootFS = make_ref<PosixSourceAccessor>();
|
||||||
@@ -208,6 +214,30 @@ ref<SourceAccessor> getFSSourceAccessor()
|
|||||||
|
|
||||||
ref<SourceAccessor> makeFSSourceAccessor(std::filesystem::path root, bool trackLastModified)
|
ref<SourceAccessor> makeFSSourceAccessor(std::filesystem::path root, bool trackLastModified)
|
||||||
{
|
{
|
||||||
|
AutoCloseFD fd = toDescriptor(
|
||||||
|
::open(
|
||||||
|
root.c_str(),
|
||||||
|
O_RDONLY |
|
||||||
|
#ifndef _WIN32
|
||||||
|
O_NOFOLLOW | O_CLOEXEC
|
||||||
|
#endif
|
||||||
|
));
|
||||||
|
|
||||||
|
if (!fd) {
|
||||||
|
if (errno == ELOOP)
|
||||||
|
/* Use a plain old PosixSourceAccessor for symlinks. Should probably just
|
||||||
|
read the link here into a MemorySourceAccessor. */
|
||||||
|
return make_ref<PosixSourceAccessor>(std::move(root), trackLastModified);
|
||||||
|
throw SysError("opening file %s", PathFmt(root));
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ::stat st;
|
||||||
|
if (::fstat(fd.get(), &st))
|
||||||
|
throw SysError("getting status of %s", PathFmt(root));
|
||||||
|
|
||||||
|
if (S_ISDIR(st.st_mode))
|
||||||
|
return makeDirectorySourceAccessor(std::move(fd), std::move(root), trackLastModified);
|
||||||
|
|
||||||
return make_ref<PosixSourceAccessor>(std::move(root), trackLastModified);
|
return make_ref<PosixSourceAccessor>(std::move(root), trackLastModified);
|
||||||
}
|
}
|
||||||
} // namespace nix
|
} // namespace nix
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
#include "nix/util/file-system.hh"
|
#include "nix/util/file-system.hh"
|
||||||
|
#include "nix/util/file-system-at.hh"
|
||||||
#include "nix/util/signals.hh"
|
#include "nix/util/signals.hh"
|
||||||
#include "nix/util/finally.hh"
|
#include "nix/util/finally.hh"
|
||||||
#include "nix/util/serialise.hh"
|
#include "nix/util/serialise.hh"
|
||||||
@@ -49,7 +50,8 @@ void readFull(int fd, char * buf, size_t count)
|
|||||||
pollFD(fd, POLLIN);
|
pollFD(fd, POLLIN);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
throw SysError("reading from file");
|
auto savedErrno = errno;
|
||||||
|
throw SysError(savedErrno, "reading from file %s", PathFmt(descriptorToPath(fd)));
|
||||||
}
|
}
|
||||||
if (res == 0)
|
if (res == 0)
|
||||||
throw EndOfFile("unexpected end-of-file");
|
throw EndOfFile("unexpected end-of-file");
|
||||||
@@ -72,7 +74,8 @@ void writeFull(int fd, std::string_view s, bool allowInterrupts)
|
|||||||
pollFD(fd, POLLOUT);
|
pollFD(fd, POLLOUT);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
throw SysError("writing to file");
|
auto savedErrno = errno;
|
||||||
|
throw SysError(savedErrno, "writing to file %s", PathFmt(descriptorToPath(fd)));
|
||||||
}
|
}
|
||||||
if (res > 0)
|
if (res > 0)
|
||||||
s.remove_prefix(res);
|
s.remove_prefix(res);
|
||||||
@@ -95,8 +98,10 @@ std::string readLine(int fd, bool eofOk, char terminator)
|
|||||||
pollFD(fd, POLLIN);
|
pollFD(fd, POLLIN);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
default:
|
default: {
|
||||||
throw SysError("reading a line");
|
auto savedErrno = errno;
|
||||||
|
throw SysError(savedErrno, "reading a line from %s", PathFmt(descriptorToPath(fd)));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else if (rd == 0) {
|
} else if (rd == 0) {
|
||||||
if (eofOk)
|
if (eofOk)
|
||||||
@@ -203,4 +208,17 @@ void unix::closeOnExec(int fd)
|
|||||||
throw SysError("setting close-on-exec flag");
|
throw SysError("setting close-on-exec flag");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void syncDescriptor(Descriptor fd)
|
||||||
|
{
|
||||||
|
int result =
|
||||||
|
#if defined(__APPLE__)
|
||||||
|
::fcntl(fd, F_FULLFSYNC)
|
||||||
|
#else
|
||||||
|
::fsync(fd)
|
||||||
|
#endif
|
||||||
|
;
|
||||||
|
if (result == -1)
|
||||||
|
throw NativeSysError("fsync file descriptor %1%", fd);
|
||||||
|
}
|
||||||
|
|
||||||
} // namespace nix
|
} // namespace nix
|
||||||
@@ -23,6 +23,8 @@
|
|||||||
# define HAVE_FCHMODAT2 0
|
# define HAVE_FCHMODAT2 0
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#include "util-unix-config-private.hh"
|
||||||
|
|
||||||
namespace nix {
|
namespace nix {
|
||||||
|
|
||||||
#ifdef __linux__
|
#ifdef __linux__
|
||||||
@@ -71,8 +73,10 @@ void unix::fchmodatTryNoFollow(Descriptor dirFd, const CanonPath & path, mode_t
|
|||||||
if (res < 0) {
|
if (res < 0) {
|
||||||
if (errno == ENOSYS)
|
if (errno == ENOSYS)
|
||||||
fchmodat2Unsupported.test_and_set();
|
fchmodat2Unsupported.test_and_set();
|
||||||
else
|
else {
|
||||||
throw SysError("fchmodat2 '%s' relative to parent directory", path.rel());
|
auto savedErrno = errno;
|
||||||
|
throw SysError(savedErrno, "fchmodat2 %s", PathFmt(descriptorToPath(dirFd) / path.rel()));
|
||||||
|
}
|
||||||
} else
|
} else
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -80,18 +84,20 @@ void unix::fchmodatTryNoFollow(Descriptor dirFd, const CanonPath & path, mode_t
|
|||||||
|
|
||||||
#ifdef __linux__
|
#ifdef __linux__
|
||||||
AutoCloseFD pathFd = ::openat(dirFd, path.rel_c_str(), O_PATH | O_NOFOLLOW | O_CLOEXEC);
|
AutoCloseFD pathFd = ::openat(dirFd, path.rel_c_str(), O_PATH | O_NOFOLLOW | O_CLOEXEC);
|
||||||
if (!pathFd)
|
if (!pathFd) {
|
||||||
|
auto savedErrno = errno;
|
||||||
throw SysError(
|
throw SysError(
|
||||||
"opening '%s' relative to parent directory to get an O_PATH file descriptor (fchmodat2 is unsupported)",
|
savedErrno,
|
||||||
path.rel());
|
"opening %s to get an O_PATH file descriptor (fchmodat2 is unsupported)",
|
||||||
|
PathFmt(descriptorToPath(dirFd) / path.rel()));
|
||||||
|
}
|
||||||
|
|
||||||
struct ::stat st;
|
/* Possible to use with O_PATH fd since
|
||||||
/* Possible since https://github.com/torvalds/linux/commit/55815f70147dcfa3ead5738fd56d3574e2e3c1c2 (3.6) */
|
* https://github.com/torvalds/linux/commit/55815f70147dcfa3ead5738fd56d3574e2e3c1c2 (3.6) */
|
||||||
if (::fstat(pathFd.get(), &st) == -1)
|
auto st = fstat(pathFd.get());
|
||||||
throw SysError("statting '%s' relative to parent directory via O_PATH file descriptor", path.rel());
|
|
||||||
|
|
||||||
if (S_ISLNK(st.st_mode))
|
if (S_ISLNK(st.st_mode))
|
||||||
throw SysError(EOPNOTSUPP, "can't change mode of symlink '%s' relative to parent directory", path.rel());
|
throw SysError(EOPNOTSUPP, "can't change mode of symlink %s", PathFmt(descriptorToPath(dirFd) / path.rel()));
|
||||||
|
|
||||||
static std::atomic_flag dontHaveProc{};
|
static std::atomic_flag dontHaveProc{};
|
||||||
if (!dontHaveProc.test()) {
|
if (!dontHaveProc.test()) {
|
||||||
@@ -101,8 +107,11 @@ void unix::fchmodatTryNoFollow(Descriptor dirFd, const CanonPath & path, mode_t
|
|||||||
if (int res = ::chmod(selfProcFdPath.c_str(), mode); res == -1) {
|
if (int res = ::chmod(selfProcFdPath.c_str(), mode); res == -1) {
|
||||||
if (errno == ENOENT)
|
if (errno == ENOENT)
|
||||||
dontHaveProc.test_and_set();
|
dontHaveProc.test_and_set();
|
||||||
else
|
else {
|
||||||
throw SysError("chmod '%s' ('%s' relative to parent directory)", selfProcFdPath, path);
|
auto savedErrno = errno;
|
||||||
|
throw SysError(
|
||||||
|
savedErrno, "chmod %s (%s)", selfProcFdPath, PathFmt(descriptorToPath(dirFd) / path.rel()));
|
||||||
|
}
|
||||||
} else
|
} else
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -122,8 +131,10 @@ void unix::fchmodatTryNoFollow(Descriptor dirFd, const CanonPath & path, mode_t
|
|||||||
#endif
|
#endif
|
||||||
);
|
);
|
||||||
|
|
||||||
if (res == -1)
|
if (res == -1) {
|
||||||
throw SysError("fchmodat '%s' relative to parent directory", path.rel());
|
auto savedErrno = errno;
|
||||||
|
throw SysError(savedErrno, "fchmodat %s", PathFmt(descriptorToPath(dirFd) / path.rel()));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static Descriptor
|
static Descriptor
|
||||||
@@ -161,8 +172,7 @@ openFileEnsureBeneathNoSymlinksIterative(Descriptor dirFd, const CanonPath & pat
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (errno == ENOTDIR) /* Path component might be a symlink. */ {
|
if (errno == ENOTDIR) /* Path component might be a symlink. */ {
|
||||||
struct ::stat st;
|
if (auto st = maybeFstatat(getParentFd(), CanonPath(component)); st && S_ISLNK(st->st_mode))
|
||||||
if (::fstatat(getParentFd(), component.c_str(), &st, AT_SYMLINK_NOFOLLOW) == 0 && S_ISLNK(st.st_mode))
|
|
||||||
throw SymlinkNotAllowed(path2);
|
throw SymlinkNotAllowed(path2);
|
||||||
errno = ENOTDIR; /* Restore the errno. */
|
errno = ENOTDIR; /* Restore the errno. */
|
||||||
} else if (errno == ELOOP) {
|
} else if (errno == ELOOP) {
|
||||||
@@ -206,11 +216,69 @@ OsString readLinkAt(Descriptor dirFd, const CanonPath & path)
|
|||||||
checkInterrupt();
|
checkInterrupt();
|
||||||
buf.resize(bufSize);
|
buf.resize(bufSize);
|
||||||
ssize_t rlSize = ::readlinkat(dirFd, path.rel_c_str(), buf.data(), bufSize);
|
ssize_t rlSize = ::readlinkat(dirFd, path.rel_c_str(), buf.data(), bufSize);
|
||||||
if (rlSize == -1)
|
if (rlSize == -1) {
|
||||||
throw SysError("reading symbolic link '%1%' relative to parent directory", path.rel());
|
auto savedErrno = errno;
|
||||||
else if (rlSize < bufSize)
|
throw SysError(savedErrno, "reading symbolic link %1%", PathFmt(descriptorToPath(dirFd) / path.rel()));
|
||||||
|
} else if (rlSize < bufSize)
|
||||||
return {buf.data(), static_cast<std::size_t>(rlSize)};
|
return {buf.data(), static_cast<std::size_t>(rlSize)};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static void symlinkAt(Descriptor dirFd, const CanonPath & path, const OsString & target)
|
||||||
|
{
|
||||||
|
assert(!path.isRoot());
|
||||||
|
assert(!path.rel().starts_with('/')); /* Just in case the invariant is somehow broken. */
|
||||||
|
if (::symlinkat(target.c_str(), dirFd, path.rel_c_str()) == -1) {
|
||||||
|
auto savedErrno = errno;
|
||||||
|
throw SysError(
|
||||||
|
savedErrno, "creating symlink %1% -> %2%", PathFmt(descriptorToPath(dirFd) / path.rel()), target);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void createFileSymlinkAt(Descriptor dirFd, const CanonPath & path, const OsString & target)
|
||||||
|
{
|
||||||
|
symlinkAt(dirFd, path, target);
|
||||||
|
}
|
||||||
|
|
||||||
|
void createDirectorySymlinkAt(Descriptor dirFd, const CanonPath & path, const OsString & target)
|
||||||
|
{
|
||||||
|
symlinkAt(dirFd, path, target);
|
||||||
|
}
|
||||||
|
|
||||||
|
void createUnknownSymlinkAt(Descriptor dirFd, const CanonPath & path, const OsString & target)
|
||||||
|
{
|
||||||
|
symlinkAt(dirFd, path, target);
|
||||||
|
}
|
||||||
|
|
||||||
|
void createDirectoryAt(Descriptor dirFd, const CanonPath & path)
|
||||||
|
{
|
||||||
|
assert(!path.isRoot());
|
||||||
|
assert(!path.rel().starts_with('/')); /* Just in case the invariant is somehow broken. */
|
||||||
|
if (::mkdirat(dirFd, path.rel_c_str(), 0777) == -1) {
|
||||||
|
auto savedErrno = errno;
|
||||||
|
throw SysError(savedErrno, "creating directory %1%", PathFmt(descriptorToPath(dirFd) / path.rel()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
PosixStat fstat(Descriptor fd)
|
||||||
|
{
|
||||||
|
PosixStat st;
|
||||||
|
if (::fstat(fd, &st)) {
|
||||||
|
auto savedErrno = errno;
|
||||||
|
throw SysError(savedErrno, "getting status of %s", PathFmt(descriptorToPath(fd)));
|
||||||
|
}
|
||||||
|
return st;
|
||||||
|
}
|
||||||
|
|
||||||
|
PosixStat fstatat(Descriptor dirFd, const CanonPath & path)
|
||||||
|
{
|
||||||
|
assert(!path.isRoot());
|
||||||
|
PosixStat st;
|
||||||
|
if (::fstatat(dirFd, path.rel_c_str(), &st, AT_SYMLINK_NOFOLLOW)) {
|
||||||
|
auto savedErrno = errno;
|
||||||
|
throw SysError(savedErrno, "getting status of %s", PathFmt(descriptorToPath(dirFd) / path.rel()));
|
||||||
|
}
|
||||||
|
return st;
|
||||||
|
}
|
||||||
|
|
||||||
} // namespace nix
|
} // namespace nix
|
||||||
@@ -23,9 +23,9 @@
|
|||||||
|
|
||||||
namespace nix {
|
namespace nix {
|
||||||
|
|
||||||
Descriptor openDirectory(const std::filesystem::path & path)
|
Descriptor openDirectory(const std::filesystem::path & path, bool followFinalSymlink)
|
||||||
{
|
{
|
||||||
return open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
|
return open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC | (followFinalSymlink ? 0 : O_NOFOLLOW));
|
||||||
}
|
}
|
||||||
|
|
||||||
Descriptor openFileReadonly(const std::filesystem::path & path)
|
Descriptor openFileReadonly(const std::filesystem::path & path)
|
||||||
@@ -46,11 +46,44 @@ Descriptor openNewFileForWrite(const std::filesystem::path & path, mode_t mode,
|
|||||||
return open(path.c_str(), flags, mode);
|
return open(path.c_str(), flags, mode);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
std::filesystem::path descriptorToPath(Descriptor fd)
|
||||||
|
{
|
||||||
|
if (fd == STDIN_FILENO)
|
||||||
|
return "<stdin>";
|
||||||
|
if (fd == STDOUT_FILENO)
|
||||||
|
return "<stdout>";
|
||||||
|
if (fd == STDERR_FILENO)
|
||||||
|
return "<stderr>";
|
||||||
|
|
||||||
|
#if defined(__linux__)
|
||||||
|
try {
|
||||||
|
return readLink("/proc/self/fd/" + std::to_string(fd));
|
||||||
|
} catch (SystemError &) {
|
||||||
|
}
|
||||||
|
#elif HAVE_F_GETPATH
|
||||||
|
/* F_GETPATH requires PATH_MAX buffer per POSIX */
|
||||||
|
char buf[PATH_MAX];
|
||||||
|
if (fcntl(fd, F_GETPATH, buf) != -1)
|
||||||
|
return buf;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* Fallback for unknown fd or unsupported platform */
|
||||||
|
return "<fd " + std::to_string(fd) + ">";
|
||||||
|
}
|
||||||
|
|
||||||
std::filesystem::path defaultTempDir()
|
std::filesystem::path defaultTempDir()
|
||||||
{
|
{
|
||||||
return getEnvNonEmpty("TMPDIR").value_or("/tmp");
|
return getEnvNonEmpty("TMPDIR").value_or("/tmp");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
PosixStat lstat(const std::filesystem::path & path)
|
||||||
|
{
|
||||||
|
PosixStat st;
|
||||||
|
if (::lstat(path.c_str(), &st))
|
||||||
|
throw SysError("getting status of %s", PathFmt(path));
|
||||||
|
return st;
|
||||||
|
}
|
||||||
|
|
||||||
void setWriteTime(
|
void setWriteTime(
|
||||||
const std::filesystem::path & path, time_t accessedTime, time_t modificationTime, std::optional<bool> optIsSymlink)
|
const std::filesystem::path & path, time_t accessedTime, time_t modificationTime, std::optional<bool> optIsSymlink)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -8,6 +8,12 @@ configdata_unix.set(
|
|||||||
description : 'Optionally used for changing the files and symlinks.',
|
description : 'Optionally used for changing the files and symlinks.',
|
||||||
)
|
)
|
||||||
|
|
||||||
|
configdata_unix.set(
|
||||||
|
'HAVE_F_GETPATH',
|
||||||
|
cxx.has_header_symbol('fcntl.h', 'F_GETPATH').to_int(),
|
||||||
|
description : 'Optionally used for getting the path of a file descriptor (macOS).',
|
||||||
|
)
|
||||||
|
|
||||||
# Check for each of these functions, and create a define like `#define
|
# Check for each of these functions, and create a define like `#define
|
||||||
# HAVE_CLOSE_RANGE 1`.
|
# HAVE_CLOSE_RANGE 1`.
|
||||||
check_funcs_unix = [
|
check_funcs_unix = [
|
||||||
|
|||||||
@@ -45,9 +45,9 @@ void writeFull(HANDLE handle, std::string_view s, bool allowInterrupts)
|
|||||||
checkInterrupt();
|
checkInterrupt();
|
||||||
DWORD res;
|
DWORD res;
|
||||||
if (!WriteFile(handle, s.data(), s.size(), &res, NULL)) {
|
if (!WriteFile(handle, s.data(), s.size(), &res, NULL)) {
|
||||||
// Do this because `handleToPath` will overwrite the last error.
|
// Do this because `descriptorToPath` will overwrite the last error.
|
||||||
auto lastError = GetLastError();
|
auto lastError = GetLastError();
|
||||||
auto path = handleToPath(handle);
|
auto path = descriptorToPath(handle);
|
||||||
throw WinError(lastError, "writing to file %d:%s", handle, PathFmt(path));
|
throw WinError(lastError, "writing to file %d:%s", handle, PathFmt(path));
|
||||||
}
|
}
|
||||||
if (res > 0)
|
if (res > 0)
|
||||||
@@ -148,4 +148,10 @@ off_t lseek(HANDLE h, off_t offset, int whence)
|
|||||||
return newPos.QuadPart;
|
return newPos.QuadPart;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void syncDescriptor(Descriptor fd)
|
||||||
|
{
|
||||||
|
if (!::FlushFileBuffers(fd))
|
||||||
|
throw WinError("FlushFileBuffers file descriptor %1%", fd);
|
||||||
|
}
|
||||||
|
|
||||||
} // namespace nix
|
} // namespace nix
|
||||||
@@ -4,8 +4,9 @@
|
|||||||
#include "nix/util/file-path.hh"
|
#include "nix/util/file-path.hh"
|
||||||
#include "nix/util/source-accessor.hh"
|
#include "nix/util/source-accessor.hh"
|
||||||
|
|
||||||
|
#include <span>
|
||||||
|
|
||||||
#include <fileapi.h>
|
#include <fileapi.h>
|
||||||
#include <error.h>
|
|
||||||
#define WIN32_LEAN_AND_MEAN
|
#define WIN32_LEAN_AND_MEAN
|
||||||
#include <windows.h>
|
#include <windows.h>
|
||||||
#include <winioctl.h>
|
#include <winioctl.h>
|
||||||
@@ -88,8 +89,8 @@ HANDLE openSymlinkAt(Descriptor dirFd, const CanonPath & path)
|
|||||||
assert(!path.isRoot());
|
assert(!path.isRoot());
|
||||||
assert(!path.rel().starts_with('/')); /* Just in case the invariant is somehow broken. */
|
assert(!path.rel().starts_with('/')); /* Just in case the invariant is somehow broken. */
|
||||||
|
|
||||||
std::wstring wpath = string_to_os_string(path.rel());
|
auto wpath = std::filesystem::path(path.rel()).make_preferred();
|
||||||
return ntOpenAt(dirFd, wpath, FILE_READ_ATTRIBUTES | SYNCHRONIZE, FILE_OPEN_REPARSE_POINT);
|
return ntOpenAt(dirFd, wpath.c_str(), FILE_READ_ATTRIBUTES | SYNCHRONIZE, FILE_OPEN_REPARSE_POINT);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -156,13 +157,13 @@ OsString readSymlinkTarget(HANDLE linkHandle)
|
|||||||
size_t path_buf_offset = offsetof(ReparseDataBuffer, SymbolicLinkReparseBuffer.PathBuffer[0]);
|
size_t path_buf_offset = offsetof(ReparseDataBuffer, SymbolicLinkReparseBuffer.PathBuffer[0]);
|
||||||
|
|
||||||
if (out < path_buf_offset) {
|
if (out < path_buf_offset) {
|
||||||
auto fullPath = handleToPath(linkHandle);
|
auto fullPath = descriptorToPath(linkHandle);
|
||||||
throw WinError(
|
throw WinError(
|
||||||
DWORD{ERROR_REPARSE_TAG_INVALID}, "invalid reparse data for %d:%s", linkHandle, PathFmt(fullPath));
|
DWORD{ERROR_REPARSE_TAG_INVALID}, "invalid reparse data for %d:%s", linkHandle, PathFmt(fullPath));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (reparse->ReparseTag != IO_REPARSE_TAG_SYMLINK) {
|
if (reparse->ReparseTag != IO_REPARSE_TAG_SYMLINK) {
|
||||||
auto fullPath = handleToPath(linkHandle);
|
auto fullPath = descriptorToPath(linkHandle);
|
||||||
throw WinError(DWORD{ERROR_REPARSE_TAG_INVALID}, "not a symlink: %d:%s", linkHandle, PathFmt(fullPath));
|
throw WinError(DWORD{ERROR_REPARSE_TAG_INVALID}, "not a symlink: %d:%s", linkHandle, PathFmt(fullPath));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -179,7 +180,7 @@ OsString readSymlinkTarget(HANDLE linkHandle)
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (path_buf_offset + name_offset + name_length > out) {
|
if (path_buf_offset + name_offset + name_length > out) {
|
||||||
auto fullPath = handleToPath(linkHandle);
|
auto fullPath = descriptorToPath(linkHandle);
|
||||||
throw WinError(
|
throw WinError(
|
||||||
DWORD{ERROR_REPARSE_TAG_INVALID}, "invalid symlink data for %d:%s", linkHandle, PathFmt(fullPath));
|
DWORD{ERROR_REPARSE_TAG_INVALID}, "invalid symlink data for %d:%s", linkHandle, PathFmt(fullPath));
|
||||||
}
|
}
|
||||||
@@ -191,6 +192,54 @@ OsString readSymlinkTarget(HANDLE linkHandle)
|
|||||||
return {target_start, target_len};
|
return {target_start, target_len};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Write symlink target to an open file handle using reparse point.
|
||||||
|
*
|
||||||
|
* @param handle Open file handle (must have GENERIC_WRITE access)
|
||||||
|
* @param target The symlink target (what it points to)
|
||||||
|
*/
|
||||||
|
void writeSymlinkTarget(HANDLE handle, const std::filesystem::path & target)
|
||||||
|
{
|
||||||
|
/* Build the reparse data buffer for a symbolic link.
|
||||||
|
Layout: SubstituteName and PrintName stored consecutively in PathBuffer.
|
||||||
|
We use the same string for both. */
|
||||||
|
size_t targetBytes = target.native().size() * sizeof(wchar_t);
|
||||||
|
size_t bufSize = offsetof(ReparseDataBuffer, SymbolicLinkReparseBuffer.PathBuffer) + targetBytes * 2;
|
||||||
|
std::vector<uint8_t> buf(bufSize, 0);
|
||||||
|
|
||||||
|
auto * reparse = reinterpret_cast<ReparseDataBuffer *>(buf.data());
|
||||||
|
reparse->ReparseTag = IO_REPARSE_TAG_SYMLINK;
|
||||||
|
reparse->ReparseDataLength =
|
||||||
|
static_cast<unsigned short>(bufSize - offsetof(ReparseDataBuffer, SymbolicLinkReparseBuffer));
|
||||||
|
reparse->Reserved = 0;
|
||||||
|
|
||||||
|
auto & symlink = reparse->SymbolicLinkReparseBuffer;
|
||||||
|
/* SubstituteName comes first */
|
||||||
|
symlink.SubstituteNameOffset = 0;
|
||||||
|
symlink.SubstituteNameLength = static_cast<unsigned short>(targetBytes);
|
||||||
|
/* PrintName follows SubstituteName */
|
||||||
|
symlink.PrintNameOffset = static_cast<unsigned short>(targetBytes);
|
||||||
|
symlink.PrintNameLength = static_cast<unsigned short>(targetBytes);
|
||||||
|
/* SYMLINK_FLAG_RELATIVE = 1 for relative symlinks, 0 for absolute */
|
||||||
|
symlink.Flags = target.is_relative() ? 1 : 0;
|
||||||
|
|
||||||
|
/* Copy target into PathBuffer twice (SubstituteName and PrintName) */
|
||||||
|
memcpy(symlink.PathBuffer, target.c_str(), targetBytes);
|
||||||
|
memcpy(reinterpret_cast<char *>(symlink.PathBuffer) + targetBytes, target.c_str(), targetBytes);
|
||||||
|
|
||||||
|
DWORD bytesReturned;
|
||||||
|
if (!DeviceIoControl(
|
||||||
|
handle,
|
||||||
|
FSCTL_SET_REPARSE_POINT,
|
||||||
|
buf.data(),
|
||||||
|
static_cast<DWORD>(bufSize),
|
||||||
|
nullptr,
|
||||||
|
0,
|
||||||
|
&bytesReturned,
|
||||||
|
nullptr))
|
||||||
|
throw WinError("setting reparse point for symlink");
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check if a handle refers to a reparse point (e.g., symlink).
|
* Check if a handle refers to a reparse point (e.g., symlink).
|
||||||
*
|
*
|
||||||
@@ -210,6 +259,115 @@ bool isReparsePoint(HANDLE handle)
|
|||||||
|
|
||||||
} // namespace windows
|
} // namespace windows
|
||||||
|
|
||||||
|
OsString readLinkAt(Descriptor dirFd, const CanonPath & path)
|
||||||
|
{
|
||||||
|
AutoCloseFD linkHandle(openSymlinkAt(dirFd, path));
|
||||||
|
return readSymlinkTarget(linkHandle.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
void createFileSymlinkAt(Descriptor dirFd, const CanonPath & path, const OsString & target)
|
||||||
|
{
|
||||||
|
assert(!path.isRoot());
|
||||||
|
assert(!path.rel().starts_with('/')); /* Just in case the invariant is somehow broken. */
|
||||||
|
|
||||||
|
auto wpath = std::filesystem::path(path.rel()).make_preferred();
|
||||||
|
|
||||||
|
/* Create the file that will become the symlink */
|
||||||
|
AutoCloseFD handle(ntOpenAt(
|
||||||
|
dirFd, wpath.c_str(), GENERIC_WRITE | DELETE, FILE_NON_DIRECTORY_FILE | FILE_OPEN_REPARSE_POINT, FILE_CREATE));
|
||||||
|
|
||||||
|
writeSymlinkTarget(handle.get(), target);
|
||||||
|
}
|
||||||
|
|
||||||
|
void createDirectorySymlinkAt(Descriptor dirFd, const CanonPath & path, const OsString & target)
|
||||||
|
{
|
||||||
|
assert(!path.isRoot());
|
||||||
|
assert(!path.rel().starts_with('/')); /* Just in case the invariant is somehow broken. */
|
||||||
|
|
||||||
|
auto wpath = std::filesystem::path(path.rel()).make_preferred();
|
||||||
|
|
||||||
|
/* Create the directory that will become the symlink */
|
||||||
|
AutoCloseFD handle(ntOpenAt(
|
||||||
|
dirFd, wpath.c_str(), GENERIC_WRITE | DELETE, FILE_DIRECTORY_FILE | FILE_OPEN_REPARSE_POINT, FILE_CREATE));
|
||||||
|
|
||||||
|
writeSymlinkTarget(handle.get(), target);
|
||||||
|
}
|
||||||
|
|
||||||
|
void createUnknownSymlinkAt(Descriptor dirFd, const CanonPath & path, const OsString & target)
|
||||||
|
{
|
||||||
|
assert(!path.isRoot());
|
||||||
|
assert(!path.rel().starts_with('/')); /* Just in case the invariant is somehow broken. */
|
||||||
|
|
||||||
|
/* Resolve target path to determine if it's a directory.
|
||||||
|
Target is relative to the symlink's parent directory. */
|
||||||
|
std::filesystem::path targetPath(target);
|
||||||
|
std::filesystem::path resolvedTarget;
|
||||||
|
|
||||||
|
if (targetPath.is_absolute()) {
|
||||||
|
resolvedTarget = targetPath;
|
||||||
|
} else {
|
||||||
|
/* Get the symlink's parent directory path and resolve target relative to it */
|
||||||
|
auto symlinkDir = descriptorToPath(dirFd);
|
||||||
|
if (auto parent = path.parent())
|
||||||
|
symlinkDir /= parent->rel();
|
||||||
|
resolvedTarget = symlinkDir / targetPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Check if target is a directory. If we can't stat it (e.g., dangling symlink),
|
||||||
|
fall back to file symlink. */
|
||||||
|
std::error_code ec;
|
||||||
|
auto status = std::filesystem::status(resolvedTarget, ec);
|
||||||
|
bool isDirectory = !ec && std::filesystem::is_directory(status);
|
||||||
|
|
||||||
|
if (isDirectory)
|
||||||
|
createDirectorySymlinkAt(dirFd, path, target);
|
||||||
|
else
|
||||||
|
createFileSymlinkAt(dirFd, path, target);
|
||||||
|
}
|
||||||
|
|
||||||
|
void createDirectoryAt(Descriptor dirFd, const CanonPath & path)
|
||||||
|
{
|
||||||
|
assert(!path.isRoot());
|
||||||
|
assert(!path.rel().starts_with('/')); /* Just in case the invariant is somehow broken. */
|
||||||
|
|
||||||
|
auto wpath = std::filesystem::path(path.rel()).make_preferred();
|
||||||
|
|
||||||
|
/* Create the directory. The handle is immediately closed. */
|
||||||
|
AutoCloseFD handle(ntOpenAt(dirFd, wpath.c_str(), FILE_TRAVERSE | SYNCHRONIZE, FILE_DIRECTORY_FILE, FILE_CREATE));
|
||||||
|
}
|
||||||
|
|
||||||
|
PosixStat fstat(Descriptor fd)
|
||||||
|
{
|
||||||
|
BY_HANDLE_FILE_INFORMATION info;
|
||||||
|
if (!GetFileInformationByHandle(fd, &info))
|
||||||
|
throw WinError("getting file information for %s", PathFmt(descriptorToPath(fd)));
|
||||||
|
|
||||||
|
PosixStat st;
|
||||||
|
windows::statFromFileInfo(
|
||||||
|
st,
|
||||||
|
info.dwFileAttributes,
|
||||||
|
info.ftCreationTime,
|
||||||
|
info.ftLastAccessTime,
|
||||||
|
info.ftLastWriteTime,
|
||||||
|
info.nFileSizeHigh,
|
||||||
|
info.nFileSizeLow,
|
||||||
|
info.nNumberOfLinks);
|
||||||
|
|
||||||
|
return st;
|
||||||
|
}
|
||||||
|
|
||||||
|
PosixStat fstatat(Descriptor dirFd, const CanonPath & path)
|
||||||
|
{
|
||||||
|
assert(!path.isRoot());
|
||||||
|
|
||||||
|
auto wpath = std::filesystem::path(path.rel()).make_preferred();
|
||||||
|
|
||||||
|
/* Open the file without following symlinks */
|
||||||
|
AutoCloseFD handle(ntOpenAt(dirFd, wpath.c_str(), FILE_READ_ATTRIBUTES | SYNCHRONIZE, FILE_OPEN_REPARSE_POINT));
|
||||||
|
|
||||||
|
return fstat(handle.get());
|
||||||
|
}
|
||||||
|
|
||||||
Descriptor openFileEnsureBeneathNoSymlinks(
|
Descriptor openFileEnsureBeneathNoSymlinks(
|
||||||
Descriptor dirFd, const CanonPath & path, ACCESS_MASK desiredAccess, ULONG createOptions, ULONG createDisposition)
|
Descriptor dirFd, const CanonPath & path, ACCESS_MASK desiredAccess, ULONG createOptions, ULONG createDisposition)
|
||||||
{
|
{
|
||||||
@@ -301,10 +459,4 @@ Descriptor openFileEnsureBeneathNoSymlinks(
|
|||||||
return finalHandle;
|
return finalHandle;
|
||||||
}
|
}
|
||||||
|
|
||||||
OsString readLinkAt(Descriptor dirFd, const CanonPath & path)
|
|
||||||
{
|
|
||||||
AutoCloseFD linkHandle(windows::openSymlinkAt(dirFd, path));
|
|
||||||
return windows::readSymlinkTarget(linkHandle.get());
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace nix
|
} // namespace nix
|
||||||
@@ -23,7 +23,7 @@ void setWriteTime(
|
|||||||
warn("Changing file times is not yet implemented on Windows, path is %s", PathFmt(path));
|
warn("Changing file times is not yet implemented on Windows, path is %s", PathFmt(path));
|
||||||
}
|
}
|
||||||
|
|
||||||
Descriptor openDirectory(const std::filesystem::path & path)
|
Descriptor openDirectory(const std::filesystem::path & path, bool followFinalSymlink)
|
||||||
{
|
{
|
||||||
return CreateFileW(
|
return CreateFileW(
|
||||||
path.c_str(),
|
path.c_str(),
|
||||||
@@ -31,7 +31,7 @@ Descriptor openDirectory(const std::filesystem::path & path)
|
|||||||
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
|
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
|
||||||
/*lpSecurityAttributes=*/nullptr,
|
/*lpSecurityAttributes=*/nullptr,
|
||||||
OPEN_EXISTING,
|
OPEN_EXISTING,
|
||||||
FILE_FLAG_BACKUP_SEMANTICS,
|
FILE_FLAG_BACKUP_SEMANTICS | (followFinalSymlink ? 0 : FILE_FLAG_OPEN_REPARSE_POINT),
|
||||||
/*hTemplateFile=*/nullptr);
|
/*hTemplateFile=*/nullptr);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -83,7 +83,7 @@ void deletePath(const std::filesystem::path & path, uint64_t & bytesFreed)
|
|||||||
deletePath(path);
|
deletePath(path);
|
||||||
}
|
}
|
||||||
|
|
||||||
std::filesystem::path windows::handleToPath(HANDLE handle)
|
std::filesystem::path descriptorToPath(Descriptor handle)
|
||||||
{
|
{
|
||||||
std::vector<wchar_t> buf(0x100);
|
std::vector<wchar_t> buf(0x100);
|
||||||
DWORD dw = GetFinalPathNameByHandleW(handle, buf.data(), buf.size(), FILE_NAME_OPENED);
|
DWORD dw = GetFinalPathNameByHandleW(handle, buf.data(), buf.size(), FILE_NAME_OPENED);
|
||||||
@@ -105,4 +105,67 @@ std::filesystem::path windows::handleToPath(HANDLE handle)
|
|||||||
return std::filesystem::path{std::wstring{buf.data(), dw}};
|
return std::filesystem::path{std::wstring{buf.data(), dw}};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
time_t windows::fileTimeToUnixTime(const FILETIME & ft)
|
||||||
|
{
|
||||||
|
/* FILETIME is 100-nanosecond intervals since January 1, 1601 UTC.
|
||||||
|
Unix time is seconds since January 1, 1970 UTC.
|
||||||
|
Difference is 11644473600 seconds. */
|
||||||
|
ULARGE_INTEGER ull;
|
||||||
|
ull.LowPart = ft.dwLowDateTime;
|
||||||
|
ull.HighPart = ft.dwHighDateTime;
|
||||||
|
return static_cast<time_t>(ull.QuadPart / 10000000ULL - 11644473600ULL);
|
||||||
|
}
|
||||||
|
|
||||||
|
void windows::statFromFileInfo(
|
||||||
|
PosixStat & st,
|
||||||
|
DWORD dwFileAttributes,
|
||||||
|
const FILETIME & ftCreationTime,
|
||||||
|
const FILETIME & ftLastAccessTime,
|
||||||
|
const FILETIME & ftLastWriteTime,
|
||||||
|
DWORD nFileSizeHigh,
|
||||||
|
DWORD nFileSizeLow,
|
||||||
|
DWORD nNumberOfLinks)
|
||||||
|
{
|
||||||
|
memset(&st, 0, sizeof(st));
|
||||||
|
|
||||||
|
/* Determine file type */
|
||||||
|
if (dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
|
||||||
|
st.st_mode = S_IFLNK | 0777;
|
||||||
|
} else if (dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
|
||||||
|
st.st_mode = S_IFDIR | 0755;
|
||||||
|
} else {
|
||||||
|
st.st_mode = S_IFREG | 0644;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* File size (only meaningful for regular files) */
|
||||||
|
st.st_size = (static_cast<int64_t>(nFileSizeHigh) << 32) | nFileSizeLow;
|
||||||
|
|
||||||
|
/* Timestamps */
|
||||||
|
st.st_atime = fileTimeToUnixTime(ftLastAccessTime);
|
||||||
|
st.st_mtime = fileTimeToUnixTime(ftLastWriteTime);
|
||||||
|
st.st_ctime = fileTimeToUnixTime(ftCreationTime);
|
||||||
|
|
||||||
|
st.st_nlink = nNumberOfLinks;
|
||||||
|
st.st_uid = 0;
|
||||||
|
st.st_gid = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
PosixStat lstat(const std::filesystem::path & path)
|
||||||
|
{
|
||||||
|
WIN32_FILE_ATTRIBUTE_DATA attrData;
|
||||||
|
if (!GetFileAttributesExW(path.c_str(), GetFileExInfoStandard, &attrData))
|
||||||
|
throw WinError("getting status of %s", PathFmt(path));
|
||||||
|
|
||||||
|
PosixStat st;
|
||||||
|
windows::statFromFileInfo(
|
||||||
|
st,
|
||||||
|
attrData.dwFileAttributes,
|
||||||
|
attrData.ftCreationTime,
|
||||||
|
attrData.ftLastAccessTime,
|
||||||
|
attrData.ftLastWriteTime,
|
||||||
|
attrData.nFileSizeHigh,
|
||||||
|
attrData.nFileSizeLow);
|
||||||
|
return st;
|
||||||
|
}
|
||||||
|
|
||||||
} // namespace nix
|
} // namespace nix
|
||||||
@@ -43,8 +43,8 @@ void removeOldGenerations(std::filesystem::path dir)
|
|||||||
std::string link;
|
std::string link;
|
||||||
try {
|
try {
|
||||||
link = readLink(path);
|
link = readLink(path);
|
||||||
} catch (std::filesystem::filesystem_error & e) {
|
} catch (SystemError & e) {
|
||||||
if (e.code() == std::errc::no_such_file_or_directory)
|
if (e.is(std::errc::no_such_file_or_directory))
|
||||||
continue;
|
continue;
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1419,7 +1419,6 @@ static int main_nix_env(int argc, char ** argv)
|
|||||||
replaceSymlink(defaultChannelsDir(profilesDirOpts), nixExprPath / "channels");
|
replaceSymlink(defaultChannelsDir(profilesDirOpts), nixExprPath / "channels");
|
||||||
if (!isRootUser())
|
if (!isRootUser())
|
||||||
replaceSymlink(rootChannelsDir(profilesDirOpts), nixExprPath / "channels_root");
|
replaceSymlink(rootChannelsDir(profilesDirOpts), nixExprPath / "channels_root");
|
||||||
} catch (std::filesystem::filesystem_error &) {
|
|
||||||
} catch (Error &) {
|
} catch (Error &) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user